Today we’ll be talking about the basics of dictionaries.
Here’s the video version of the article:
A dictionary is an unordered set of key-value pairs.
Table of Contents
The Features of Dictionaries
Here are the main features of dictionaries:
– Dictionaries are mutable: they can be changed, shrink or grow.
– Dictionaries are defined in curly braces.
– Dictionaries can contain lists.
– Dictionaries can be contained in lists.
– The elements in a dictionary are accessed by keys and not by indices.
– The keys in a dictionary are unique.
– Each key is mapped to a value.
– The values may be any data type.
– The keys may be only immutable data types.
– Dictionaries don’t support the sequence operations of lists, tuples and strings.
– Dictionaries are the only representative of the built-in mapping type.
Defining a Dictionary
Let’s define a dictionary:
In each pair the first element is the key and the other is the value. The two are separated by a colon.
>>> countries_capitals = {"Canada" : "Ottawa", "Norway" : "Oslo", "Egypt" : "Cairo", "Australia" : "Canberra", "Italy" : "Rome"}
Accessing Dictionary Elements
We access the elements of a dictionary by key using square brackets:
>>> countries_capitals["Norway"]
'Oslo'
If we use a key which is not contained in the dictionary, we get an error.
>>> countries_capitals["Nigeria"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Nigeria'
If we try to access an element by index, we get an error, too. Dictionaries are unordered. Indices don’t work.
>>> countries_capitals[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
Adding Elements to a Dictionary
In order to add a new entry to the dictionary, we use a new key and set its value:
>>> countries_capitals["Austria"] = "Vienna"
>>> countries_capitals
{'Canada': 'Ottawa', 'Norway': 'Oslo', 'Egypt': 'Cairo', 'Australia': 'Canberra', 'Italy': 'Rome', 'Austria': 'Vienna'}
Changing Values
In order to change a value in a dictionary, we assign the new value to the key:
>>> scores = {"Tess" : 17, "Jackie" : 22}
>>> scores["Jackie"] = 35
>>> scores
{'Tess': 17, 'Jackie': 35}
Empty Dictionary
We can create an empty dictionary by using an empty pair of curly braces:
>>> scores = {}
>>> scores
{}
Then we can add elements:
>>> scores["Amanda"] = 246
>>> scores
{'Amanda': 246}
Key and Value Uniqueness
The keys must be unique. If we try to define a dictionary with repetitive keys, only the last value will be selected:
>>> first_names = {"Smith" : "Peter", "Jackson" : "Luke", "Smith" : "Natalie", "Smith" : "Patricia", "Brown" : "John"}
>>> first_names
{'Smith': 'Patricia', 'Jackson': 'Luke', 'Brown': 'John'}
The values don’t have to be unique:
>>> birth_months = {"Jannet" : "March", "Julia" : "October", "Ron" : "March", "Emma" : "June", "Louise" : "June"}
>>> birth_months["Jannet"]
'March'
>>> birth_months["Ron"]
'March'
Nested Dictionaries
The values can be simple or complex data types. In particular, dictionaries may be nested inside other dictionaries. You may also want to read my Nested List and Dictionary Basics article where I cover this topic.
Here’s an example with values being other dictionaries:
>>> lectures = {"math" : {"lecturer" : "John Plus", "room" : 110},
... "programming" : {"lecturer" : "Amanda Python", "room" : 145},
... "physics" : {"lecturer" : "Louise Particle", "room" : 201}}
And here’s how we can access a value inside the inner dictionary:
>>> lectures["physics"]["lecturer"]
'Louise Particle'
We can use the values in one dictionary as the keys in another. Here we have two dictionaries:
1) the English-German fruit dictionary:
>>> english_german = {"apple" : "Apfel", "pear" : "Birne", "orange" : "Orange"}
and 2) the German-Spanish fruit dictionary:
>>> german_spanish = {"Apfel" : "manzana", "Birne" : "pera", "Orange" : "naranja"}
In the first dictionary we check the value of “apple”. It’s “Apfel”:
>>> english_german["apple"]
'Apfel'
It so happens that “Apfel” is a key in the second dictionary. So we can find its value either like so:
>>> german_spanish[“Apfel”]
'manzana'
or like so:
>>> german_spanish[english_german["apple"]]
'manzana'
We can create a dictionary of dictionaries:
>>> fruit_dictionaries = {"English-German" : english_german, "German-Spanish" : german_spanish}
Now we can find the word we need in the dictionary we need. So, let’s see in the German-Spanish dictionary what’s the Spanish for “Orange”:
>>> fruit_dictionaries["German-Spanish"]["Orange"]
'naranja'
Key Types
The keys must be immutable types. If you try to use a mutable type like a list or another dictionary, you’ll get an error:
>>> codes = {[4,16] : "entryCode"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
You can use a tuple because it’s immutable:
>>> codes = {(4,16) : "entryCode"}
>>> codes
{(4, 16): 'entryCode'}
But you can’t use a tuple which contains mutable types, like lists:
>>> codes = {(4,[16, 41]) : "entryCode"}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Membership
Using the ‘in’ and ‘not in’ membership operators we can check whether a key is contained in the dictionary:
>>> "shark" in animals
True
>>> "ladybug" not in animals
True
Deleting Dictionary Items and the Whole Dictionary
We can delete a key-value pair using del dict[key]:
>>> del animals["wasp"]
>>> animals
{'cat': 'mammal', 'shark': 'fish', 'boa': 'reptile'}
We also use the del statement to delete the whole dictionary:
>>> colors = {"blood" : "red", "snow" : "white", "coal" : "black", "grass" : "green"}
>>> del colors
Now if we try to print the dictionary, we get an error because the dictionary doesn’t exist anymore:
>>> colors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'colors' is not defined
If you want to keep the dictionary but clear its content, you should use the clear method:
>>> capitals = {"California" : "Sacramento", "Georgia" : "Atlanta"}
>>> capitals.clear()
What we get is an empty dictionary:
>>> capitals
{}
Number of Elements
You can use the len(dict) function to determine the number of the key-value pairs:
>>> animals = {"cat" : "mammal", "shark" : "fish", "wasp" : "insect", "boa" : "reptile"}
>>> len(animals)
4