Python Dictionary
Python Dictionaries
Section titled “Python Dictionaries”Dictionaries are Python’s fundamental mapping type. They store collections of key-value pairs, where each key must be unique and immutable (like strings, numbers, or tuples containing only immutable elements). Values can be of any type and can be duplicated.
Dictionaries are defined using curly braces {}. An empty dictionary is {}. Items are separated by commas, with a colon : separating each key from its value.
# Creating dictionariesempty_dict = {}student = { 'name': 'Zara', 'age': 17, 'courses': ['Math', 'Physics']}config = dict(host='localhost', port=8080) # Alternative using dict()Important Note: As of Python 3.7+, standard dictionaries remember the insertion order of items. In earlier versions (3.6 and below), dictionaries were unordered.
Accessing Values in Dictionary
Section titled “Accessing Values in Dictionary”You access the value associated with a key using square bracket notation [].
student = {'name': 'Zara', 'age': 17, 'class': 'First'}
print(f"Student's Name: {student['name']}")print(f"Student's Age: {student['age']}")Output:
Student's Name: ZaraStudent's Age: 17Accessing a key that doesn’t exist using [] will raise a KeyError.
student = {'name': 'Zara', 'age': 17}
# This will cause an error:# print(f"Student's Grade: {student['grade']}")To safely access keys, you can use the get() method, which returns None (or a specified default value) if the key is not found.
grade = student.get('grade') # Returns Nonedefault_grade = student.get('grade', 'N/A') # Returns 'N/A'print(f"Grade (safe access): {grade}")print(f"Grade (with default): {default_grade}")Updating Dictionary
Section titled “Updating Dictionary”You can add new key-value pairs or modify existing ones using the assignment operator = with square bracket notation.
student = {'name': 'Zara', 'age': 17, 'class': 'First'}
# Update existing entrystudent['age'] = 18
# Add new entrystudent['school'] = "Springfield High"student['contact'] = {'email': 'zara@example.com'} # Values can be complex
print(f"Updated Age: {student['age']}")print(f"School: {student['school']}")print(f"Contact Info: {student['contact']}")print(f"Full dictionary: {student}")Output:
Updated Age: 18School: Springfield HighContact Info: {'email': 'zara@example.com'}Full dictionary: {'name': 'Zara', 'age': 18, 'class': 'First', 'school': 'Springfield High', 'contact': {'email': 'zara@example.com'}}You can also merge dictionaries using the update() method or the merge operator | (Python 3.9+).
more_info = {'city': 'Shelbyville', 'age': 19} # Note 'age' overlapsstudent.update(more_info) # Updates existing keys, adds new onesprint(f"After update(): {student}")
# Using merge operator (Python 3.9+)extra = {'country': 'USA'}merged_student = student | extraprint(f"After merge |: {merged_student}")Delete Dictionary Elements
Section titled “Delete Dictionary Elements”You can remove individual key-value pairs, clear the entire dictionary, or delete the dictionary object itself.
student = {'name': 'Zara', 'age': 18, 'class': 'First', 'school': 'Springfield High'}
# Remove entry with key 'class' using deldel student['class']print(f"After del student['class']: {student}")
# Remove entry with key 'school' using pop() (returns the value)school = student.pop('school')print(f"Removed school: {school}")print(f"After pop('school'): {student}")
# Remove the last inserted item (Python 3.7+)last_item = student.popitem()print(f"Removed last item: {last_item}")print(f"After popitem(): {student}")
# Remove all entries from the dictionarystudent.clear()print(f"After clear(): {student}")
# Delete the dictionary object entirelydel student# print(student) # This would now raise a NameErrorOutput (will vary slightly for popitem based on exact insertion order):
After del student['class']: {'name': 'Zara', 'age': 18, 'school': 'Springfield High'}Removed school: Springfield HighAfter pop('school'): {'name': 'Zara', 'age': 18}Removed last item: ('age', 18)After popitem(): {'name': 'Zara'}After clear(): {}Properties of Dictionary Keys
Section titled “Properties of Dictionary Keys”Dictionary keys have two important properties:
- Keys Must Be Unique: A dictionary cannot have duplicate keys. If you assign a value to an existing key, the original value is overwritten.
- Keys Must Be Immutable: Keys must be of a hashable type. This includes numbers (int, float), strings, booleans, and tuples containing only immutable elements. Lists, dictionaries, or sets cannot be used as keys because they are mutable (their contents can change).
Example (Duplicate Keys):
dict_dup = { 'name': 'Zara', 'age': 7, 'name': 'Manni' # This assignment overwrites the previous 'name'}
print(f"dict_dup['name']: {dict_dup['name']}") # Output: ManniExample (Immutable Keys):
# Valid keysvalid_keys = { 10: 'Number', 'user': 'Admin', (1, 2): 'Tuple Key', True: 'Boolean Key'}print(valid_keys)
# Invalid key (list is mutable)# invalid_keys = {# ['list_key']: 'This will fail'# }# TypeError: unhashable type: 'list'Dictionary Methods and Operations
Section titled “Dictionary Methods and Operations”Python dictionaries support various built-in functions and methods:
Common Functions:
Section titled “Common Functions:”| Function | Description |
|---|---|
len(dict) | Returns the number of key-value pairs (items) in the dictionary. |
str(dict) | Returns a printable string representation of the dictionary. |
type(variable) | Returns the type of the variable. If it’s a dictionary, returns <class 'dict'>. |
Key Dictionary Methods:
Section titled “Key Dictionary Methods:”| Method | Description |
|---|---|
dict.clear() | Removes all items from the dictionary. |
dict.copy() | Returns a shallow copy of the dictionary. |
dict.fromkeys(seq[, value]) | Creates a new dictionary with keys from seq and values set to value (defaults to None). (Class method) |
dict.get(key[, default]) | Returns the value for key if key is in the dictionary, else default. If default is not given, it defaults to None. |
dict.items() | Returns a view object displaying a list of a dictionary’s key-value tuple pairs. Changes to the dictionary are reflected in the view. |
dict.keys() | Returns a view object displaying a list of a dictionary’s keys. Changes to the dictionary are reflected in the view. |
dict.values() | Returns a view object displaying a list of a dictionary’s values. Changes to the dictionary are reflected in the view. |
dict.pop(key[, default]) | Removes the specified key and returns the corresponding value. If the key is not found, default is returned if given, otherwise a KeyError is raised. |
dict.popitem() | Removes and returns the last inserted key-value pair (as a tuple). Raises KeyError if the dictionary is empty. (Before Python 3.7, removed an arbitrary pair). |
dict.setdefault(key[, default]) | If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None. |
dict.update([other]) | Updates the dictionary with the key-value pairs from other (another dictionary or iterable of key-value pairs), overwriting existing keys. |
Checking for Key Existence:
Section titled “Checking for Key Existence:”The preferred way to check if a key exists is using the in operator:
student = {'name': 'Zara', 'age': 18}
if 'age' in student: print("Age key exists.")
if 'grade' not in student: print("Grade key does not exist.")Note: The dict.has_key(key) method used in Python 2 is deprecated and removed in Python 3. Use the in operator instead.
Dictionary Comprehensions
Section titled “Dictionary Comprehensions”Similar to list comprehensions, you can create dictionaries concisely:
squares = {x: x*x for x in range(1, 6)}# squares will be: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}print(squares)