3.3. Dictionaries#

Amanda R. Kube Jotte

The next collection of data we will discuss is the dictionary. Like lists, dictionaries are built into Python and do not require you to load any additional libraries. Dictionaries are Python’s built-in mapping tool. They map values onto keys and are composed of key:value pairs.

Creating Dictionaries#

An empty dictionary can be created using {} as follows:

dictionary = {}

Where lists are indexed using numbers (for example my_list[0:3]), dictionaries are indexed using their keys. Below, we create a dictionary named my_dict which has two keys which are both strings and two values, one of which is a float and the other a string.

value1 = 2.4
value2 = "value here"

my_dict = {
    'key1': value1,
    'key2': value2
}

my_dict
{'key1': 2.4, 'key2': 'value here'}

If we want to access a value in this dictionary, we use its key.

my_dict['key1']
2.4

Dictionary keys must be unique and immutable. They can be strings, numbers, or tuples. Lists and dictionaries (that can be changed) are not allowed as dictionary keys.

We can also create dictionaries from lists of key:value pairs presented as tuples using dict().

names_list = [(1,"Susanna"),(2,"Evelyn"),(3,"Amanda")]
dict(names_list)
{1: 'Susanna', 2: 'Evelyn', 3: 'Amanda'}

Dictionary of Dictionaries#

In the previous two examples the values were all strings or all integers. As we saw when creating my_dict, values in a dictionary do not need to be of the same data type. Values can include integers, floats, strings, lists, …, or even other dictionaries! One useful application of a dictionary is as an address book.

Here we create a dictionary of dictionaries. (What are the keys of the top level dictionary? What are the keys of the second-level dictionary?)

addresses = {
    "Bill": {'phone':3125551234, 'email': 'bill@internet.com'},
    "Mary": {'phone':3125559876, 'email': 'mary@web.net'},
    "Sue": {'phone':3125552468, 'email': 'sue@email.edu'}
}
addresses
{'Bill': {'phone': 3125551234, 'email': 'bill@internet.com'},
 'Mary': {'phone': 3125559876, 'email': 'mary@web.net'},
 'Sue': {'phone': 3125552468, 'email': 'sue@email.edu'}}

If I want to know Mary’s information, I can access it using the key Mary.

addresses['Mary']
{'phone': 3125559876, 'email': 'mary@web.net'}

This returns a dictionary of information for Mary. If I am only interested in a certain piece of information, for example her phone number, I can access it using the phone key.

addresses['Mary']['phone']
3125559876

This returns only her phone number. Perhaps we can’t remember which keys are in the address book. We can use list() to list all of the keys.

list(addresses)
['Bill', 'Mary', 'Sue']

Note

The list() function takes in a grouping of data and uses it to create a list. In the case of a dictionary, it creates a list of keys. In the case of a string, it creates a list of characters. It can also be used to create an empty list, if you don’t give it any input.

Changing Dictionaries#

We can also add elements to a dictionary…

addresses['Dan'] = {'phone':3125555678} # Not all values need to have the same data type or length
addresses
{'Bill': {'phone': 3125551234, 'email': 'bill@internet.com'},
 'Mary': {'phone': 3125559876, 'email': 'mary@web.net'},
 'Sue': {'phone': 3125552468, 'email': 'sue@email.edu'},
 'Dan': {'phone': 3125555678}}

…and delete elements from a dictionary using del.

del addresses['Mary']
addresses
{'Bill': {'phone': 3125551234, 'email': 'bill@internet.com'},
 'Sue': {'phone': 3125552468, 'email': 'sue@email.edu'},
 'Dan': {'phone': 3125555678}}

Keys are unique so the following code would not add a new key, but rather change the value of the key:

addresses['Dan'] = {'phone':3125555678,'email': 'none'}
addresses
{'Bill': {'phone': 3125551234, 'email': 'bill@internet.com'},
 'Sue': {'phone': 3125552468, 'email': 'sue@email.edu'},
 'Dan': {'phone': 3125555678, 'email': 'none'}}

Working with Dictionary Methods#

Dictionaries come with built-in methods that make it easy to access and update their contents. We will go through a few of the most commonly used ones, but you can always find out more by reading the Python documentation.

The .keys() method returns all of the keys in the dictionary.

student = {"name": "Alice", "age": 20}
print(student.keys())
# dict_keys(['name', 'age'])

Notice that the output isn’t a plain list—it’s something called a view object, which we’ll talk more about shortly.


.values()#

The .values() method returns all of the values stored in the dictionary.

print(student.values())
# dict_values(['Alice', 20])

This is useful if you only care about the information stored in the dictionary, not the keys.


.items()#

The .items() method returns both keys and values together, as tuples. Each tuple is a (key, value) pair.

print(student.items())
# dict_items([('name', 'Alice'), ('age', 20)])

This is especially handy when you want to loop through the dictionary and need access to both the keys and the values.


.update()#

The .update() method allows you to add new key–value pairs or overwrite existing ones.

student.update({"age": 21, "major": "Data Science"})
print(student)
# {'name': 'Alice', 'age': 21, 'major': 'Data Science'}

Here, the value for "age" was updated from 20 to 21, and a new key "major" was added.


A Note on View Objects#

The results of .keys(), .values(), and .items() are view objects, not static lists. A view object acts like a “live window” into the dictionary:

  • If the dictionary changes, the view updates automatically.

  • If you need a snapshot (a fixed list of the current contents), you can convert the view into a list.

keys_view = student.keys()
print(keys_view)  # dict_keys(['name', 'age', 'major'])

# Add another key
student["GPA"] = 3.8
print(keys_view)  # dict_keys(['name', 'age', 'major', 'GPA'])

# Convert to a list if you need a fixed snapshot
print(list(student.keys()))  # ['name', 'age', 'major', 'GPA']

This dynamic behavior is powerful, but it can be surprising if you’re not expecting it.

student = {"name": "Alice", "age": 20}
print(student.keys())
dict_keys(['name', 'age'])

Note

The output of .keys() isn’t a plain list – it’s something called a view object. A view object acts like a “live window” into the dictionary. If the dictionary changes, the view updates automatically. This dynamic behavior is powerful, but it can be surprising if you’re not expecting it.

If you need a snapshot (a fixed list of the current contents), you can convert the view into a list using list().

Similar to .keys(), the .values() method returns all of the values stored in the dictionary. Its output is also a view object.

print(student.items())
dict_items([('name', 'Alice'), ('age', 20)])

This is useful if you only care about the information stored in the dictionary, not the keys.

The .items() method returns both keys and values together, as tuples. Each tuple is a (key, value) pair and is also a view object.

print(student.items())
dict_items([('name', 'Alice'), ('age', 20)])

Be careful when using .keys(), .values(), and .items() because, unless you convert them into a list, they will automatically update whenever the dictionary itself is updated.

In contrast, the .update() method does not return a view object. Instead, it mutates the dictionary directly by adding new key–value pairs or overwriting existing ones. Like many mutating methods in Python (for example, list.insert()), its return value is None. You don’t need to reassign the variable because .update() modifies the dictionary in place.

student.update({"age": 21, "major": "Data Science"})
print(student)
{'name': 'Alice', 'age': 21, 'major': 'Data Science'}

Dictionaries are powerful because they let us store values under unique keys. But sometimes, we don’t care about the values at all; we only care about the keys themselves. For example, we might just want to know whether something exists in our collection, without needing to store extra information alongside it.

This is where another data structure, the set, comes in. Sets are designed specifically for working with unique elements and membership tests, making them a natural next step after dictionaries.