Pulsars
0 %
Log inSign up

Dictionaries

The dictionary: associating a key with a value

The dictionary: associating a key with a value

A list arranges values in an order, accessible by their position (index). A dictionary, on the other hand, associates each value with a key of your choice, a bit like a real dictionary associates a word with its definition, or a phone directory associates a name with a phone number.

In Python, you create a dictionary with curly braces, writing each key/value pair:

annuaire = {
    "Sam": "0601020304",
    "Alex": "0611223344"
}

To access a value, you use its key in square brackets, not a numeric index:

print(annuaire["Sam"])   # (displays 0601020304)

Common mistake: asking for a key that doesn't exist in the dictionary. This causes a KeyError:

print(annuaire["Camille"])   # (causes a KeyError, Camille doesn't exist)

To avoid this risk, you can use the get method, which returns None (or a default value of your choice) instead of causing an error:

print(annuaire.get("Camille", "unknown"))   # (displays unknown, no error)

You can add or modify an entry simply by assigning a value to a key:

annuaire["Camille"] = "0655667788"   # (adds a new entry)
annuaire["Sam"] = "0699999999"        # (modifies an existing entry)

A dictionary, like a list, is mutable: you can add, change, or remove entries after it's created, without having to recreate the whole thing.