python dictionaries data-structures

Dictionaries in Python

Learning objectives

By the end of this pill you will be able to:

  • create and initialise dictionaries (dict);
  • access, add, modify and remove key-value pairs;
  • iterate over keys, values and pairs;
  • use useful methods such as get, keys, values, items.

What is a dictionary

A dictionary is a data structure that associates a value with every key. It is similar to a “vocabulary”: every word (key) has its definition (value). In Python it is defined with curly braces { } using the key: value syntax.

student = {
    "name": "Luca",
    "surname": "Rossi",
    "age": 17
}

Note: Keys must be unique and of an immutable type (strings, numbers, tuples). Values can be of any type.

Accessing values

print(student["name"])    # Luca
print(student["age"])     # 17

If you access a non-existent key, Python raises an error. To avoid this, use get().

print(student.get("class", "not found"))
# prints "not found"

Adding and modifying

Adding or modifying an entry is very simple:

student["class"] = "5A"    # adds a new pair
student["age"] = 18        # modifies an existing value
print(student)

Removing elements

pop() and del

student.pop("surname")    # removes the key and returns the value
del student["class"]      # deletes the key without returning it

clear()

student.clear()           # empties the dictionary
print(student)            # {}

Iterating over a dictionary

subjects = {"italian": 7, "maths": 8, "cs": 9}

# iterate over keys
for k in subjects:
    print(k)

# iterate over values
for v in subjects.values():
    print(v)

# iterate over key-value pairs
for k, v in subjects.items():
    print(k, "=", v)

Useful methods

  • keys() → returns all keys.
  • values() → returns all values.
  • items() → returns key-value pairs.
  • update(dict2) → adds or updates multiple pairs from another dictionary.
info = {"name": "Luca"}
info.update({"age": 18, "city": "Turin"})
print(info)   # {"name": "Luca", "age": 18, "city": "Turin"}

Differences from lists and sets

  • Lists manage ordered collections of values accessible by a numeric index.
  • Sets manage collections of unique values, with no order and no indices.
  • Dictionaries associate a value with each key, enabling fast lookups.
lst  = ["Luca", "Marco"]
s    = {"Luca", "Marco"}
dct  = {"student1": "Luca", "student2": "Marco"}

In brief: use a dict when you need to associate a key with a value, like a “contacts book” or a “register”.