Python Dictionaries

A dictionary is a built-in Python collection that stores data as key-value pairs, letting you look things up by a meaningful name instead of a numeric position.

What is a dictionary?

A dictionary maps each key to a value, much like a real-world phone book maps a person's name to their number. Instead of remembering that an item sits at index 3, you retrieve it by its key. Dictionaries are written with curly braces, and each entry is a key followed by a colon and then its value.

Creating a dictionary

person = {
    "name": "Ada",
    "job": "engineer",
    "age": 36
}

print(person)
print(person["name"])

In the example above, the strings "name", "job", and "age" are the keys, while "Ada", "engineer", and 36 are the values they point to. You can mix value types freely: a single dictionary can hold strings, numbers, lists, and even other dictionaries.

Key properties

  • Ordered: since Python 3.7, dictionaries remember the order in which items were inserted.
  • Changeable: you can add, update, and remove entries after the dictionary is created.
  • No duplicate keys: each key must be unique, and assigning to an existing key overwrites its value.
  • Keys must be immutable: strings, numbers, and tuples work as keys, but lists do not.

Duplicate keys are not allowed

scores = {
    "math": 90,
    "math": 95
}

print(scores)  # {'math': 95} - the later value wins
Note: Use len(my_dict) to count how many key-value pairs a dictionary contains, and type(my_dict) to confirm its class is <class 'dict'>.

The dict() constructor

Building a dictionary with dict()

city = dict(name="Paris", country="France", population=2148000)

print(city)
print(len(city))

The dict() function is a handy alternative to curly braces, especially when your keys are simple names. Whichever style you choose, the resulting object behaves the same way.

Exercise: Python Dictionaries

What does dict.keys() return compared to dict.values()?