5️⃣ 📔 Python Dictionary
A dictionary is a set with 🔐 key:value pairs. It is designed to lookup values based on the 🔑 key to return a 🔒 value. An example is a dictionary of words (key) with a definition for each word (value).
💡 Create Dictionary
Like the list and set and unlike a tuple, a dict of length 1 is defined without an extra trailing comma {'i':i}. If key values are repeated, the last definition of the key:value pair is used (e.g. {'i':2,'i':3} result is {'i':3}).
Create a dictionary with values {'i':1,'x':2.7,'e':3.8e3}.
print(d)
{'i': 1, 'x': 2.7, 'e': 3800.0}
Another way to define the dictionary is with the dict() function.
📝 Print Dictionary
Print the dictionary and verify the object type as a dict with the type() function.
type(d)
{'i': 1, 'x': 2.7, 'e': 3800.0} dict
🔓 Access Value with 🔑 Key
Read the value of a dictionary item using the key.
1
Set the value of a dictionary item also using the key.
d['i']
2
📑 Unpack Dictionary
Each key of a dictionary is accessed when d is used as an iterator in a for loop.
print(k)
i x e
Use d.items() to create a generator to separate the key:value pairs.
print(k,v)
i 2 x 2.7 e 3800.0
🪆 Nested Dictionary
A dictionary z can be a sub-element of another dictionary d as a nested dictionary.
Reference the sub-elements by including an additional square bracket at the end to designate the item such as d['z']['a'].
d['z']['a']
11
🧦 Copy Dictionary
The copy function creates a shallow copy of dictionary d as a new dictionary d2. A shallow copy is a duplication of the first layer of a dictionary but the lower layers are copied as references.
When d2['x'] is set to 3, there is no corresponding change to d['x'].
print(d)
print(d2)
{'x': 1, 'y': 2, 'z': {'a': 11, 'b': 12}} {'x': 3, 'y': 2, 'z': {'a': 11, 'b': 12}}
However, when d2['z']['a'] is changed to 13, there is a corresponding change to d['z']['a'] because both share the same reference to dictionary z.
print(d)
print(d2)
{'x': 1, 'y': 2, 'z': {'a': 13, 'b': 12}} {'x': 3, 'y': 2, 'z': {'a': 13, 'b': 12}}
A deep copy creates a completely independent dictionary for all layers. Use the function copy.deepcopy() to create a deep copy. The value of d['z']['a'] doesn't change when d3['z']['a'] is set to 14.
d3 = copy.deepcopy(d)
d3['z']['a'] = 14
print(d)
print(d3)
{'x': 1, 'y': 2, 'z': {'a': 13, 'b': 12}} {'x': 1, 'y': 2, 'z': {'a': 14, 'b': 12}}
🔑 Dictionary Attributes and Methods with dir
Use the dir() function to list all attributes (constants, properties) and methods (functions) that are available with an object.
A dict has the following methods (functions):
- clear - clear all entries: d.clear()
- copy - create a shallow copy of the dict: d4=d.copy()
- fromkeys - create a new dictionary from listed keys: d4=d.fromkeys(['x','y'])
- get - return value for key, else return None: d.get('x')
- items - return a set-like object with a view of dictionary items: d.items()
- keys - return a set-like object with a view of dictionary keys: d.keys()
- pop - remove a key:value from dict: d.pop('x')
- popitem - remove last element from dict: d.popitem()
- setdefault - insert key with a value of None if not in dict: d.setdefault('x')
- update - update dict with key:value pairs from another dict: d.update(d2)
- values - return a dict_values object that provides a view of the dictionary values: d.values()
Because a dict is not ordered, there is no particular index for each key:value pair. The order that items are added is tracked and pop removes the most recently added key:value pair. There are also no sort functions. Convert the keys to a list to sort the dict keys.
💻 Exercise 5A
Print the values in dictionary d one at a time using a for loop that iterates through the keys.
for di in d:
print(f'key: {di}',
f'value: {d[di]}')
💻 Exercise 5B
Modify 'x':0 and add 'b':23 as key:value pairs to dictionary d. Print the elements of the dictionary to verify the change and addition.
d['x'] = 0
print(d)
d['b'] = 23
print(d)
✅ Knowledge Check
1. What is the output of the code: d = {'i':2,'i':3} ?
- Incorrect. The dictionary will not have duplicate keys. The last definition of the key:value pair will be used.
- Correct. Dictionaries in Python do not allow duplicate keys. The last definition of the key:value pair is used.
- Incorrect. The code is syntactically correct. It will just use the last definition of the key:value pair.
- Incorrect. Dictionaries in Python do not allow duplicate keys. The last definition of the key:value pair is used.
2.: How would you increment the value of key 'i' by 1 in the dictionary d? Select two correct answers.
- Correct. This is a correct way to increment the value associated with key 'i' by 1.
- Correct. This is another correct way to increment the value associated with key 'i' by 1.
- Incorrect. The code uses the variable i instead of the string 'i' as the key, which would raise a KeyError unless a variable i with a valid value exists.
- Incorrect. This is not a valid method to increment the value. The add method does not exist for integer values.