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

Avoid errors when popping a non-existent key

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

Looping Over Dictionaries

Dictionaries are iterable with a for in loop.

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

Dictionary Operators

The in membership operator works with dictionaries.

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

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

Last updated

Was this helpful?