Python dictionary

A Python dictionary is a set of pairs.

d = {'book': 97, 'pen': 145, 'note': 314}

As a real dictionary consists of words and meanings, each pair of a Python dictionary has the key and value. In the example, book is a key and 97 is a value.

Get a value by a key

Python dictionary get returns the value of a given key.

d = {
    'book': 28,
    'pen': 145,
}

a = d.get('book')
b = d.get('car')

print(a)  # 28
print(b)  # None

d doesn't have car key so b is None.

Get a default value

d = {
    'book': 97,
    'pen': 145,
}

a = d.get('book', 2)
b = d.get('car', 3)

print(a)  # 97
print(b)  # 3

d doesn't have car but get returns 3 because the second argument (option) is 3. This option is None by default.

d has book so a is 97, not 2. The option is ignored if the key exists.

Note that get resembles setdefault in Python dictionary, which returns the value if the key exists and adds the pair if the key doesn't exist. It's important to understand the difference of get and setdefault.

  • get ... can't update itself
  • setdefault ... can update itself

Count the elements of a dictionary

d = {'book': 97, 'pen': 145, 'note': 314}

c = len(d)

print(c)  # 3

The len() is a built-in function that counts elements in a dictionary, list, tuple, set, etc.

Append the key and value

d = {'x': 3, 'y': 4}

d['z'] = 5

print(d)  # {'x': 3, 'y': 4, 'z': 5}

If the key has already existed, the dictionary is updated instead appended.

d = {'x': 3, 'y': 4}

d['x'] = 5

print(d)  # {'x': 5, 'y': 4}

pop

d = {'A': 2, 'B': 5, 'C': 13}

p = d.pop('B')

print(d)  # {'A': 2, 'C': 13}
print(p)  # 5

The pop deletes an item by the key returning the value. You can't remove the key that doesn't exist.

d = {'A': 2, 'B': 5, 'C': 13}

d.pop('D')

# KeyError: 'D'

del

d = {'A': 2, 'B': 5, 'C': 13}

del d['C']

print(d)  # {'A': 2, 'B': 5}

The del is a Python built-in function that deletes an element by the key. It raises the exception if the key doesn't exist.

d = {'A': 2, 'B': 5, 'C': 13}

del d['D']

# KeyError: 'D'

clear

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}
d.clear()

print(d)  # {}

The clear() removes all the items from a dictionary. The id of the dictionary doesn't change after clearing.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

print(id(d))  # 4408171776

d.clear()

print(id(d))  # 4408171776

Get all the items of a dictionary

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

items = d.items()

print(items)  # dict_items([('CA', 'California'), ('NV', 'Nevada'), ('TX', 'Texas')])

The items() returns all pairs of a dictionary as a dict_items that can be iterated.

Iterate a dictionary

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

items = d.items()

for pair in d.items():
    print(pair)

# ('CA', 'California')
# ('NV', 'Nevada')
# ('TX', 'Texas')

Each pair of d.items() is a tuple of the key and value.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

for i in d:
    print(i)

# CA
# NV
# TX

Iterating directly over a dictionary prints only the keys.

keys()

The keys() method that returns the keys of it as a dict_keys object.

d = {'book': 24, 'pen': '5'}

keys = d.keys()

print(keys)  # dict_keys(['book', 'pen'])
print(type(keys))  # <class 'dict_keys'>

for k in keys:
    print(k)

# book
# pen

A dict_keys is an iterable, an object that can be iterated in a for loop, and not a list. The following example shows how to get the dictionary keys as list.

d = {'book': 24, 'pen': '5'}

keys = d.keys()
a = list(keys)

print(keys)  # dict_keys(['book', 'pen'])
print(a)  # ['book', 'pen']

The dict_keys object is updated by updating the dictionary.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

keys = d.keys()

d['VA'] = 'Virginia'

print(keys)  # dict_keys(['CA', 'NV', 'TX', 'VA'])

Example:

class User:

    def __init__(self, name):
        self.name = name


u = User(name='Josh')

d = u.__dict__
k = u.__dict__.keys()

print(d)  # {'name': 'Josh'}
print(k)  # dict_keys(['name'])

The __dict__ of an instance is the dictionary of properties.

values()

The values() returns the values of a dictionary as a dict_values object.

d = {'book': 24, 'pen': '5'}

values = d.values()

print(values)  # dict_values([24, '5'])
print(type(values))  # <class 'dict_values'>

for v in values:
    print(v)

# 24
# 5

A Python dictionary has the values() method that returns its values that can be iterated. The next example shows how to get the values as a list.

d = {'book': 24, 'pen': '5'}

values = d.values()
a = list(values)

print(values)  # dict_values([24, '5'])
print(a)  # [24, '5']

Empty dictionary

A dictionary with no item is an empty dictionary.

d = {'book': 97, 'pen': 145, 'note': 314}
e = {}

print(type(d))  # <class 'dict'>
print(type(e))  # <class 'dict'>

{} looks an empty set but it's a dictionary. A set is declared by the set() function.

d = {}
e = set()

print(type(d))  # <class 'dict'>
print(type(e))  # <class 'set'>

Dictionary comprehension

a = [2, 5, 8]
d = {n: n + 1 for n in a}

print(d)  # {2: 3, 5: 6, 8: 9}

The n is the "local" variable iterating a. This style is called "dictionary comprehension" in Python PEP 274. It is like list comprehension.

Example:

a = ['Apple', 'Microsoft', 'Google']
d = {i: len(i) for i in a}

print(d)  # {'Apple': 5, 'Microsoft': 9, 'Google': 6}

The dictionary comprehension can be used to create a simple dictionary from a list. Of course, you can create a dictionary from the dictionary with Python dictionary comprehension.

a = {'x': 5, 'y': 7}
d = {k: v ** 2 for k, v in a.items()}

print(d)  # {'x': 25, 'y': 49}

If you want to iterate a dictionary, use the items() in loop.

Python Dictionary

Python Tutorial