Dictionaries

A dictionary (or dict) is a collection of key:value pairs. As of Python version 3.7, dictionaries are now ordered by insertion order.

Creating a dictionary

actor = {
    'name': 'John Cleese',
    'funnyAF': True,
    'characters': ['Sir Lancelot', 'The Black Knight', 'Mr. Teabag, The Minister of Silly Walks']
}

Accessing values

print(actor['name'])

Adding and changing keys

actor['age'] = 82
actor['name'] = 'John Marwood Cleese'
print(actor)

Dictionary Methods

Dictionaries have a lot of useful methods. Here are a few:

get

"safely" access a key and optionally set a default value

keys

gets a list of all the keys

values

gets a list of all the values

items

gets a list of key-value pairs as tuples

pop

remove a key-value pair with the specified key

print(actor.get('nationality', 'Earthling')) # -> Earthling
print(actor.keys())
print(actor.values())
print(actor.items())

is_funny = actor.pop('funnyAF')
print(is_funny)
print(actor)

Avoid errors when popping a non-existent key

height = actor.pop('height') # -> KeyError
height = actor.pop('height', None)
print(height) # -> None

For more dictionary methods: https://www.w3schools.com/python/python_ref_dictionary.asp

Looping Over Dictionaries

Dictionaries are iterable with a for in loop.

for key in actor:
    print(key)

You can also loop over the lists returned by the keys, values, and items methods.

for k, v in actor.items():
    print(f'Key - {k}')
    print(f'Value - {v}')

Dictionary Operators

The in membership operator works with dictionaries.

print('name' in actor)   # -> True
print('height' in actor) # -> False

As of Python version 3.9, the | operator can merge dictionaries.

a = { 'spam': 3, 'eggs': 2 }
b = { 'bacon': 1, 'sausage': 1, 'spam': 5 }

c = a | b
print(c)

NOTE spam from b overwrote the one from a as b is the "last-seen" value (the right-hand operand).

Last updated