Dictionaries
A dictionary is a data structure that stores key:value pairs. Dictionaries are ordered, mutable and do not allow duplicates.
Dictionaries are useful when you will primarily be doing lookups, they are faster than lists since we
can get the exact value using it’s key. In a list to get an item at a specific index you will need to
Now we can look up the specific values we want. To create a dictionary, use curly braces with
keys and values separated by :
.
country_codes = {
"zambia": "+260",
"south africa": "+27",
"canada": "+1",
"tanzania": "+255"
}
To get a value we can look it up using it’s key.
code = country_codes["canada"]
Trying to get a key that doesn’t exist will result in an error. To set a additional items you will need to provide a key, value pair.
country_codes["usa"] = "+1"
You can also override the value for a key in the same way.
Looping through dictionaries
Dictionaries can be iterated over, just like lists, using the items()
method. This time, however,
you will get both the key and value in each iteration of the list.
capitals = {
"Norway": "Oslo",
"Japan": "Tokyo",
"France": "Paris"
}
for key,value in capitals.items():
print("The capital of",key,"is",value)
Looping through dictionaries can be slower than lists, so for extensive looping consider if this is the right data structure.