12. Dictionaries
By Bernd Klein. Last modified: 11 Feb 2024.
Introduction
In the preceding chapters, we delved into the fundamentals of lists, , including subtle intricacies. Now, as we progress through this chapter of our online Python course, we turn our attention to dictionaries, exploring their syntax, operators, and methods. Lists and dictionaries are indispensable components of Python programming, making Python a powerful and extremely useful programming language.
Let's begin with a straightforward example to illustrate the concept of a dictionary:
person = {
'name': 'Anna Schmidt',
'age': 28,
'city': 'Berlin',
'email': '[email protected]'
}
In Python, a dictionary is a data structure that stores key-value pairs. Let's take a closer look at our example dictionary to explain the essential details:
- A dictionary is wrapped in curly brackets
{}. - A dictionary contains keys and values.
- The keys in our dictionary are strings and are positined in front of the colons. The keys of our example dictionary are 'name', 'age', 'city', and 'email'.
- Each key is associated with a corresponding value separated by a colon
:: 'Anna Schmidt' is the value associated with the key 'name', 28 with 'age', 'Berlin' with 'city', and '[email protected]' with 'email'. - We call
- We call a key-value pair like 'name': 'Anna Schmidt' an item. So a dictionary contains an arbitrary sequence of
key:valuepairs separated by commas.
Dictionaries are useful for organizing data in a way that allows quick and easy access based on specific keys.
We can also consider a dictionary like a digital information card about a person named Anna Schmidt from Berlin, Germany and keeps track of important details in a structured way.
In this digital card:
- 'name': This is where we keep Anna's full name, which is 'Anna Schmidt'.
- 'age': Here we store Anna's age, which is 28 years old.
- 'city': This tells us where Anna lives, which is in Berlin.
- 'email': Anna's email address, which is '[email protected]', is stored here.
In the code snippet below, we demonstrate how to retrieve specific pieces of information from our dictionary, such as the 'name' or 'age', from the dictionary:
# Retrieving values
name = person['name']
age = person['age']
print("Name:", name)
print("Age:", age)
OUTPUT:
Name: Anna Schmidt Age: 28
Now, we'll illustrate how dictionaries can be modified because they are mutable. Let's consider a scenario where Anna relocates from Berlin to Freiburg, renowned as one of Germany's most picturesque cities, known for its favorable weather compared to other regions in the country.
# Anna moves to Freiburg
person['city'] = 'Freiburg'
# Updated information
print(person)
OUTPUT:
{'name': 'Anna Schmidt', 'age': 28, 'city': 'Freiburg', 'email': '[email protected]'}
Like lists, they can be easily changed, can be shrunk and grown ad libitum at run time. They shrink and grow without the necessity of making copies. Dictionaries can be contained in lists and vice versa.
Let's add Anna's gender and her favorite hobbies, which include reading, music, and programming (as she's a beginner in Python), to the existing dictionary:
person['sex'] = 'female'
person['favorite_hobbies'] = ['reading', 'music', 'programming']
person
OUTPUT:
{'name': 'Anna Schmidt',
'age': 28,
'city': 'Freiburg',
'email': '[email protected]',
'favorite_hobbies': ['reading', 'music', 'programming'],
'sex': 'female'}
Now, we remove again the gender information from the dictionary:
# Deleting gender information
del person['sex']
print(person)
OUTPUT:
{'name': 'Anna Schmidt', 'age': 28, 'city': 'Freiburg', 'email': '[email protected]', 'favorite_hobbies': ['reading', 'music', 'programming']}
Live Python training
See our Python training courses
Associative Arrays
More theoretically, we can say that dictionaries are the Python implementation of an abstract data type, known in computer science as an associative array. Associative arrays consist - like dictionaries of (key, value) pairs, such that each possible key appears at most once in the collection. Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any type of Python data. So, dictionaries are unordered key-value-pairs. Dictionaries are implemented as hash tables, and that is the reason why they are known as "Hashes" in the programming language Perl.
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists. Dictionaries belong to the built-in mapping type, but so far, they are the sole representative of this kind!
At the end of this chapter, we will demonstrate how a dictionary can be turned into one list, containing (key,value)-tuples or two lists, i.e. one with the keys and one with the values. This transformation can be done reversely as well.
Dictionary and Lists
But what's the difference between lists and dictionaries?
A list is a sequence of objects where the order matters. You can access list elements directly by their position in this order. Similarly, dictionaries are also ordered, but unlike lists, you can't access elements by their position. We can also say that contrary to lists that the order of a dictionary is not important. The order of items in a dictionary is determined by the sequence in which they were added. If we print a dictionary, we can see this ordering.
Let's demonstrate this with the following dictionary:
city_population = {
