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).

d = {'i':i,'x':x,'e':e}

💡 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}.

d = {'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.

d = dict(i=1, x=2.7, e=3.8e3)

📝 Print Dictionary

Print the dictionary and verify the object type as a dict with the type() function.

print(d)
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.

d['i']
    1

Set the value of a dictionary item also using the key.

d['i'] += 1
d['i']
    2

📑 Unpack Dictionary

Each key of a dictionary is accessed when d is used as an iterator in a for loop.

for k in d:
    print(k)
    i
    x
    e

Use d.items() to create a generator to separate the key:value pairs.

for k,v in d.items():
    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.

d = dict(x=1,y=2,z=dict(a=11,b=12))

Reference the sub-elements by including an additional square bracket at the end to designate the item such as d['z']['a'].

d = dict(x=1,y=2,z=dict(a=11,b=12))
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.

d2 = d.copy()

When d2['x'] is set to 3, there is no corresponding change to d['x'].

d2['x'] = 3
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.

d2['z']['a'] = 13
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.

import copy
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.

dir(d)

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.

print(d)
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.

print(d)
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} ?

A. {'i':2,'i':3}
Incorrect. The dictionary will not have duplicate keys. The last definition of the key:value pair will be used.
B. {'i':3}
Correct. Dictionaries in Python do not allow duplicate keys. The last definition of the key:value pair is used.
C. SyntaxError
Incorrect. The code is syntactically correct. It will just use the last definition of the key:value pair.
D. {'i':2}
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.

A. d['i'] = d['i'] + 1
Correct. This is a correct way to increment the value associated with key 'i' by 1.
B. d['i'] += 1
Correct. This is another correct way to increment the value associated with key 'i' by 1.
C. d[i] = d[i] + 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.
D. d['i'].add(1)
Incorrect. This is not a valid method to increment the value. The add method does not exist for integer values.