Dictionaries are unordered*, mutable collections of unique key/value pairs.

Items in a dictionary are indexed by keys, and not by their order like lists, tuples and strings (sequence types).

Dictionary keys must be immutable objects such as strings, numbers or tuples. Tuples can only be used as keys if they don’t contain any mutable object.

* In Python 3, dictionaries return items in the order in which they were inserted. In Python 2, the insertion order is not retained.

Dictionary basics

Dictionaries are delimited by braces or ‘curly brackets’.

Here’s how we create an empty dictionary:

>>> myDict = {}
>>> type(myDict)
<class 'dict'>

And this is how we create a new dictionary with some items:

>>> myDict = {
...     'key 1' : 'some value',
...     'key 2' : 'another value',
... }

Dictionary items must be key/value pairs. Keys and values are separated by a colon, and items are separated by a comma.

Sets are also delimited by braces, but its items are not key/value pairs.

Adding items to a dictionary

This is how we add new items to a dictionary:

>>> myDict['key 3'] = 'some other value'

Getting values from a dictionary

Dictionary values can be retrieved using their matching keys:

>>> myDict['key 2']
another value

If the dictionary does not have an item with the given key, a KeyError will be raised:

>>> myDict['key 4']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key 4'

Assigning a new value to a key

Dictionaries are mutable, so we can assign a new value to an existing key:

>>> testDict = { 'a' : 10, 'b' : 20 }
>>> testDict['a']
10
>>> testDict['a'] = 1000
>>> testDict['a']
1000

Avoiding key errors

Checking if a dictionary has a key

One of the ways to avoid key errors is by checking if a dictionary has a key before trying to access it. We can do that using the in keyword:

>>> 'key 3' in myDict
True
>>> key = 'key 4'
>>> if key in myDict:
...     myDict[key]
... else:
...     "'{}' not in dict".format(key)
'key 4' not in dict

In Python 2, this could also be done using the older syntax dict.has_key(). This method is deprecated in Python 3.

Getting values with dict.get()

Another way to avoid key errors is using the dict.get() method to access values. Instead of raising a KeyError, it returns None if a key does not exist.

>>> myDict.get('key 2')
another value
>>> myDict.get('key 4')
None

Accessing dictionary contents

The keys of a dictionary can be accessed using the dict.keys() method:

>>> myDict.keys()
dict_keys(['key 1', 'key 2', 'key 4'])

In Python 3, dict.keys() return a dynamic view object which can be iterated over and supports membership tests. In Python 2, dict.keys() returns a list of keys.

A view object can be converted into a list using the built-in function list():

>>> list(myDict.keys())
['key 1', 'key 2', 'key 4']

The values in a dictionary can be accessed using dict.values():

>>> list(myDict.values())
['some value', 'another value', 'abcdefg']

We can also use dict.items() to get a list of all items as (key, value) tuples:

>>> list(myDict.items())
[('key 1', 'some value'), ('key 2', 'another value'), ('key 4', 'abcdefg')]

Iterating over a dictionary

Depending on what we are trying to do, we can chose to iterate over the keys (and get the value inside the loop):

>>> for key in myDict.keys():
...     key, myDict[key]
('key 1', 'value')
('key 2', 'another value')
('key 3', 'some other value')

…or we can iterate through the items, unpacking key and value in the loop expression:

>>> for key, value in myDict.items():
...     key, value
('key 1', 'value')
('key 2', 'another value')
('key 3', 'some other value')

Nested dictionaries

Dictionaries may contain other dictionaries:

>>> myFontFamily = {
...     'roman' : {
...         'Regular' : {
...             'xHeight' : 500,
...             'descender' : -150,
...             'ascender' : 680,
...         }
...     }
... }

Items in nested dictionaries can be accessed by ‘chaining’ the keys of the parent dicts and the item:

>>> myFontFamily['roman']['Regular']
{'xHeight': 500, 'descender': -150, 'ascender': 680}
>>> myFontFamily['roman']['Regular']['xHeight']
430

Making copies of a dictionary

Assigning a dictionary to a new variable does not create another dictionary – just a new reference to the same dictionary object:

>>> anotherDict = myDict
>>> anotherDict is myDict
True

There are different ways to create a copy of a dictionary. One of them is using the dict.copy() method:

>>> anotherDict2 = myDict.copy()
>>> myDict is anotherDict2
False

Another way is using built-in function dict():

>>> anotherDict3 = dict(myDict)
>>> myDict is anotherDict3
False

Creating a dictionary from a list of key/value pairs

dict() can also be used to create a dictionary from a list of (key, value) tuples:

>>> dict([('frogs', 4139), ('butterflies', 4127), ('snails', 4098)])
{'frogs': 4139, 'butterflies': 4127, 'snails': 4098}
Last edited on 17/12/2018