In this tutorial, we will talk about dictionaries, another Python collection such as lists and tuples. A dictionary consists of key-value pairs. Each key maps to a corresponding value.
Dict Syntax
Imagine that you need a data structure that stores information related to a specific person. A dictionary is suitable for this purpose.
person = {
"first_name": "John",
"last_name": "Brown",
"age": 34
}
print(person)
In the example above, at line 1 we instantiate a new variable named person, which stores information in key-value pairs. To be more precise, person is a dictionary. A dictionary is written with curly brackets and each key-value pair is separated by a comma. Within each key-value pair, the syntax is: key: value. Note that the colon is strictly necessary for separating the key from the value.
Dictionaries are mutable in Python. It means that you can modify them after they are created. You can add, remove or update key-value pairs. In each key-value pair, the key can be any immutable type. In fact, strings and numbers can be always keys. Tuple can be used as keys if they contain strings, numbers or other tuples. Lists cannot be used as keys, since they are mutable objects.
So far, we have learned that the sequences, such as lists and tuples, can be indexed by numbers (or index). Instead, dictionaries are indexed by keys. You can access a specific value within a dictionary through the related key. Let’s give an example:
my_list = [3, 4, 5, 6]
item = my_list[0] # indexing for lists
# define a dictionary that associates some countries with their corresponding capitals
my_dict = {
"Italy": "Rome",
"England": "London",
"France": "Paris",
"Spain": "Madrid"
}
italian_capital = my_dict["Italy"] # indexing for dicts
print(italian_capital)
# Output: Rome
As you can see, we define a dictionary that stores the capital city for each country. In this specific case, keys are strings, which are immutable types in Python. At line 12, we access the value related to the key-value pair where key is equal to “Italy”. Looking at my_dict in the code, we easily note that the string “Rome” is the value associated with “Italy” key.
Dict Mutability
As we have discussed earlier, Python dictionaries are mutable. Each key-value pair can be updated or removed. Additionally, after a dictionary is created, it is possible to add new key-value pairs. Let’s see the aspects in the code:
person = {
"first_name": "Emily",
"last_name": "Johnson",
"age": 29
}
person["first_name"] = "Sarah" # accessing the value Emily and replace it with Sarah
print(person)
# Output:
# {'first_name': 'Sarah', 'last_name': 'Johnson', 'age': 29}
As you can see running the code above, our person dictionary has been changed at line 7. Now imagine that you want to add a new key-value pair to person. For instance, we can store information about job: is our person a full-time eployee?
person = {
"first_name": "Sarah",
"last_name": "Johnson",
"age": 29
}
person["full_time"] = False # she's not a full-time employee
print(person)
# Output:
# {'first_name': 'Sarah', 'last_name': 'Johnson', 'age': 29, 'full_time': False}
Let’s suppose now that the age key is no longer essential. Therefore, we want to delete the age key-value pair.
# Add these lines to the code above
del person["age"] # delete age
print(person)
# Output:
# {'first_name': 'Sarah', 'last_name': 'Johnson', 'full_time': False}
The age key-value pair has been successfully deleted.
Loop Dictionaries
In the previous lessons, we talked about iterating over lists and tuples. A dictionary can also be looped over.
# define a dict with person-age pairs
my_dict = {
"John": 35,
"Sarah": 45,
"Ethan": 12,
"Sophia": 23,
"Liam": 67
}
for x in my_dict:
print(x)
# Output:
# John
# Sarah
# Ethan
# Sophia
# Liam
In the example above, we use the same looping technique that we applied to lists and tuples. In this way, no error occurs. However, it only prints the keys, which is not what we want. Instead, we should consider printing the key-value pairs. So, how can we do that?
The items() dictionary method comes to our aid. This method returns a view object that displays a list of dictionary’s key-value tuple pairs. We can use it to iterate through a dictionary.
my_dict = {
"John": 35,
"Sarah": 45,
"Ethan": 12,
"Sophia": 23,
"Liam": 67
}
print(my_dict.items())
# Output:
# dict_items([('John', 35), ('Sarah', 45), ('Ethan', 12), ('Sophia', 23), ('Liam', 67)])
for x, y in my_dict.items():
print(f"{x} is {y} years old.")
# Output:
# John is 35 years old.
# Sarah is 45 years old.
# and so on...
Don’t care about the structure of what my_dict.items() returns. Basically, this method returns all the key-value tuple pairs. For this reason, this method is essential to iterate through a dictionary.
It is also possibile to obtain a view object that displays a list of all dictionary’s keys. The same is also possible for the values. Let’s see it in code:
my_dict = {
"Italy": "Rome",
"Japan": "Tokyo",
"Spain": "Madrid",
"France": "Paris"
}
all_keys = my_dict.keys() # returns all the keys
print(all_keys)
# Output:
# dict_keys(['Italy', 'Japan', 'Spain', 'France')
keys_list = list(my_dict.keys()) # convert to list to visualize better
print(keys_list)
# Output:
# ['Italy', 'Japan', 'Spain', 'France']
values_list = list(my_dict.values()) # same for values
print(values_list)
# Output:
# ['Rome', 'Tokyo', 'Madrid', 'Paris']
Note: the list() function used at line 14 and at line 20 converts the object passed as a parameter into a list.
my_tuple = (2, 4, 6, 8, 10, 12, 14) converted = list(my_tuple) print(converted) # Output: # [2, 4, 6, 8, 10, 12, 14] print(type(converted)) # Output: # <class 'list'>;