Lesson #8: Dictionaries
As you’ve already seen, dictionaries are a data type similar to arrays but work with keys and values instead of indexes. It is generally used when we have a huge amount of data. Also, dictionaries are optimized for retrieving data.
Reminder: Dictionaries are written with curly brackets, and have keys and values.
Example
“name”: “Nick”,
“age”: 29,
“address”: “52 Hefner Acres”
}
Accessing Dictionary Values
To access a value in a dictionary, enclose the corresponding key in square brackets ([]) at the end of the dictionary or a variable name assigned to a dictionary.
“name”: “Nick”,
“age”: 29,
“address”: “52 Hefner Acres”
}
print(customer[“name”]) # Nick
Adding and Removing Values
Dictionaries are mutable data structures which means you can add and remove items.
Add Value
Let’s add the name of a customer to the customers
dictionary:
“age”: 35,
“city”: “London”
}
customers[“name”] = “John”
print(customers)
Remove Value
To remove an item from a dictionary, use the del
keyword with the key for the value you want to delete.
Let’s remove the name of a customer from the customers
dictionary:
“name”: “Nick”,
“age”: 29,
“address”: “52 Hefner Acres”
}
del customers[“name”]
print(customers)
Loop Through Dictionaries
When you loop over a dictionary with a for loop, you iterate over the dictionary’s keys:
“name”: “Nick”,
“age”: 29,
“address”: “52 Hefner Acres”
}
for x in customers:
print(x) # name # age # address
The following example loop over a dictionary and prints all the values.
Example
“name”: “Nick”,
“age”: 29,
“address”: “52 Hefner Acres”
}
for x in customers:
print(customers[x]) # Nick # 29 # 52 Hefner Acres
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries. Let’s alter the customers dictionary to illustrate the following idea:
“customer1” : {
“name” : “Gustavo”,
“age” : 25
},
“customer2” : {
“name” : “Luke”,
“age” : 38
},
“customer3” : {
“name” : “Peter”,
“age” : 50
}
}
Instead of mapping customers’ names to their details, you created a dictionary that maps each customer’s name to a dictionary containing the name and the age. The value of each key is a dictionary: