Dictionaries#

Dictionaries are like lists, but indices (here denoted as keys) are not restricted to integers but can be of any immutable type. Even tuples are allowed as keys if they do not contain mutable items. Data types for keys can be mixed. Type name for dictionaries is dict.

Creating Dictionaries#

Dictionary items are defined as colon separated pairs key: value.

person = {'name': 'John', 'surname': 'Doe', 'age': 42}
print(person['name'])

person['age'] += 1
print(person['age'])
John
43

To add data to an existing dictionary simply assign to the new key:

person['gender'] = 'male'

With {} we obtain an empty dictionary.

Dictionary Methods#

Items may be removed with del(key), like for lists.

The keys method returns a list-like object containing all keys used in the dictionary. Similarly, the values method returns all values in the dictionary and the items method returns all pairs (tuples) of keys and corresponding items.

Note

Python follows the duck typing approach: If it looks like a duck, walks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

In other words: There are many object types in Python which behave like a list, but aren’t of type list. In particular, len and indexing syntax [...] may be used for such objects.