Dictionaries

A new example of a constructed type is the dictionary.

On the same principle as the dictionaries we know, a dictionary is a set of "key - value" pairs: we no longer look for an element by its position in the sequence, but by the value of its identification key.

Similarly, in a dictionary, we look for the definition of a word by searching for that word:

  • the key is the word
  • the value is its definition

Dictionary manipulation

Creating and reading a dictionary

We created tuples with parentheses, lists with brackets, for dictionaries we have curly braces:

my_tuple = ("cat", 12, 13)
my_list = ["cat", 12, 13]
my_dictionary = {"car": "four-wheeled vehicle", "bike": "two-wheeled vehicle"}

To access an element of the dictionary, it's simple:

>>> my_dictionary["car"]
four-wheeled vehicle

A dictionary can contain strings, integers, or any other type:

number_of_wheels = { "car": 4, "bike": 2}

Adding an element to a dictionary

To create a new entry in a dictionary, simply assign a value to the new key:

my_dictionary["tricycle"] = "three-wheeled vehicle"

Traversing a dictionary

We use the items() function.

Example with a for loop on one index:

for item in my_dictionary.items():
    print(item)

Example with a for loop on two indices:

for key, value in my_dictionary.items():
    print(key, value)