You are on page 1of 13

1/23/2021 Lecture on Dictionaries - Jupyter Notebook

Dictionaries (Data Structure)


Dictionaries allow us to store connected bits of information. For example, you might store a person's name and age together.

What are dictionaries?


Dictionaries are a way to store information that is connected in some way. Dictionaries store information in key-value pairs, so that any
one piece of information in a dictionary is connected to at least one other piece of information.

Dictionaries do not store their information in any particular order, so you may not get your information back in the same order you entered
it.

General Syntax
A general dictionary in Python looks something like this:

In [ ]: dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

Since the keys and values in dictionaries can be long, we often write just one key-value pair on a line. You might see dictionaries that look
more like this:

In [ ]: dictionary_name = {key_1: value_1,


key_2: value_2,
key_3: value_3,
}

In [ ]: g={'a':'dog','b':'cat'}
print(g.values())
print(g.keys())

This is a bit easier to read, especially if the values are long.

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 1/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

Example
A simple example involves modeling an actual dictionary.

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

We can get individual items out of the dictionary, by giving the dictionary's name, and the key in square brackets:

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

print("Meaning: " , python_words['list'])

print("Meaning: " , python_words['dictionary'])

print("Meaning: " , python_words['function'])

In [ ]: python_words.keys()

In [ ]: python_words.values()

In [ ]: python_words.items()

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 2/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

# Print out the items in the dictionary.


for word, meaning in python_words.items():
print("\nWord: " , word)
print("Meaning: " , meaning)

The output is identical, but we did it in 3 lines instead of 6. If we had 100 terms in our dictionary, we would still be able to print them out
with just 3 lines.

The only tricky part about using for loops with dictionaries is figuring out what to call those first two variables. The general syntax for this
for loop is:

In [ ]: for key_name, value_name in dictionary_name.items():


print(key_name) # The key is stored in whatever you called the first variable.
print(value_name) # The value associated with that key is stored in your second variable.

Common operations with dictionaries


There are a few common things you will want to do with dictionaries. These include adding new key-value pairs, modifying information in
the dictionary, and removing items from dictionaries.

Adding new key-value pairs


To add a new key-value pair, you give the dictionary name followed by the new key in square brackets, and set that equal to the new
value. We will show this by starting with an empty dictionary, and re-creating the dictionary from the example above.

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 3/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: # Create an empty dictionary.


python_words = {}

# Fill the dictionary, pair by pair.


python_words['list'] ='A collection of values that are not connected, but have an order.'
python_words['dictionary'] = 'A collection of key-value pairs.'
python_words['function'] = 'A named set of instructions that defines a set of actions in Python.'

# Print out the items in the dictionary.


for word, meaning in python_words.items():
print(word,': ', meaning)

Modifying values in a dictionary


At some point you may want to modify one of the values in your dictionary. Modifying a value in a dictionary is pretty similar to modifying
an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

print(python_words['dictionary'])

# Clarify one of the meanings.


python_words['dictionary'] = 'A collection of key-value pairs. Each key can be used to access its corresponding

print(python_words['dictionary'])

Removing key-value pairs


You may want to remove some key-value pairs from one of your dictionaries at some point. You can do this using the same del
command you learned to use with lists. To remove a key-value pair, you give the del command, followed by the name of the dictionary,
with the key that you want to delete. This removes the key and the value as a pair.

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 4/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

# Remove the word 'list' and its meaning.


python_words.pop('list')

#del python_words['list']

# Show the current set of words and meanings.


for word, meaning in python_words.items():
print(word)
print(meaning)

If you were going to work with this code, you would certainly want to put the code for displaying the dictionary into a function. Let's see
what this looks like:

In [ ]: def show_words_meanings(python_words):
# This function takes in a dictionary of python words and meanings,
# and prints out each word with its meaning.
print("\n\nThese are the Python words I know:")
for word, meaning in python_words.items():
print("\nWord: " , word)
print("Meaning: " , meaning)

python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

show_words_meanings(python_words)

# Remove the word 'list' and its meaning.


del python_words['list']

show_words_meanings(python_words)

As long as we have a nice clean function to work with, let's clean up our output a little:

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 5/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: def show_words_meanings(python_words):
# This function takes in a dictionary of python words and meanings,
# and prints out each word with its meaning.
for word, meaning in python_words.items():
print(word, meaning)

python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

show_words_meanings(python_words)

# Remove the word 'list' and its meaning.


del python_words['list']

show_words_meanings(python_words)

This is much more realistic code.

Modifying keys in a dictionary


Modifying a value in a dictionary was straightforward, because nothing else depends on the value. Modifying a key is a little harder,
because each key is used to unlock a value. We can change a key in two steps:

Make a new key, and copy the value to the new key.
Delete the old key, which also deletes the old value.

Here's what this looks like. We will use a dictionary with just one key-value pair, to keep things simple.

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 6/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: # We have a spelling mistake!


python_words = {'lisst': 'A collection of values that are not connected, but have an order.'}

# Create a new, correct key, and connect it to the old value.


# Then delete the old key.
python_words['list'] = python_words['lisst']
del python_words['lisst']

# Print the dictionary, to show that the key has changed.


print(python_words)

Looping through a dictionary


Since dictionaries are really about connecting bits of information, you will often use them in the ways described above, where you add
key-value pairs whenever you receive some new information, and then you retrieve the key-value pairs that you care about. Sometimes,
however, you will want to loop through the entire dictionary. There are several ways to do this:

You can loop through all key-value pairs;


You can loop through the keys, and pull out the values for any keys that you care about;
You can loop through the values.

Looping through all key-value pairs


This is the kind of loop that was shown in the first example. Here's what this loop looks like, in a general format:

In [ ]: my_dict = {'key_1': 'value_1',


'key_2': 'value_2',
'key_3': 'value_3',
}

for key, value in my_dict.items():


print( key, end=' ')
print(value)

This works because the method .items() pulls all key-value pairs from a dictionary into a list of tuples:

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 7/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

Looping through all keys in a dictionary


Python provides a clear syntax for looping through just the keys in a dictionary:

In [ ]: my_dict = {'key_1': 'value_1',


'key_2': 'value_2',
'key_3': 'value_3',
}

for key in my_dict.keys():


print('Key:' , key)

This is actually the default behavior of looping through the dictionary itself. So you can leave out the .keys() part, and get the exact
same behavior:

In [ ]: my_dict = {'key_1': 'value_1',


'key_2': 'value_2',
'key_3': 'value_3',
}

for key in my_dict:


print('Key:' , key)

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

# Show the words that are currently in the dictionary.


print("The following Python words have been defined:")
for word in python_words:
print("- %s" % word)

We can extend this slightly to make a program that lets you look up words. We first let the user choose a word. When the user has
chosen a word, we get the meaning for that word, and display it:

This allows the user to select one word that has been defined. If we enclose the input part of the program in a while loop, the user can
localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 8/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

see as many definitions as they'd like:

This allows the user to ask for as many meanings as they want, but it takes the word "quit" as a requested word. Let's add an elif
clause to clean up this behavior:

top

Looping through all values in a dictionary


Python provides a straightforward syntax for looping through all the values in a dictionary, as well:

In [ ]: my_dict = {'key_1': 'value_1',


'key_2': 'value_2',
'key_3': 'value_3',
}

for value in my_dict.values():


print('Value:' ,value)

Looping through a dictionary in order


Dictionaries are quite useful because they allow bits of information to be connected. One of the problems with dictionaries, however, is
that they are not stored in any particular order. When you retrieve all of the keys or values in your dictionary, you can't be sure what order
you will get them back. There is a quick and easy way to do this, however, when you want them in a particular order.

Let's take a look at the order that results from a simple call to dictionary.keys():

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

for word in python_words.keys():


print(word)

The resulting list is not in order. The list of keys can be put in order by passing the list into the sorted() function, in the line that initiates the
localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 9/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook
e esu t g st s ot o de e st o eys ca be put o de by pass g t e st to t e so ted() u ct o , t e e t at t ates t e
for loop:

In [ ]: python_words = {'list': 'A collection of values that are not connected, but have an order.',
'dictionary': 'A collection of key-value pairs.',
'function': 'A named set of instructions that defines a set of actions in Python.',
}

for word in sorted(python_words.keys()):


print(word)

Nesting
Nesting is one of the most powerful concepts we have come to so far. Nesting involves putting a list or dictionary inside another list or
dictionary. We will look at two examples here, lists inside of a dictionary and dictionaries inside of a dictionary. With nesting, the kind of
information we can model in our programs is expanded greatly.

Lists in a dictionary
A dictionary connects two pieces of information. Those two pieces of information can be any kind of data structure in Python. Let's keep
using strings for our keys, but let's try giving a list as a value.

The first example will involve storing a number of people's favorite numbers. The keys consist of people's names, and the values are lists
of each person's favorite numbers. In this first example, we will access each person's list one at a time.

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 10/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: # This program stores people's favorite numbers, and displays them.


favorite_numbers = {'eric': [3, 11, 19, 23, 42],
'ever': [2, 4, 5],
'willie': [5, 35, 120],
}

# Display each person's favorite numbers.


print("Eric's favorite numbers are:")
print(favorite_numbers['eric'])

print("\nEver's favorite numbers are:")


print(favorite_numbers['ever'])

print("\nWillie's favorite numbers are:")


print(favorite_numbers['willie'])

Dictionaries in a dictionary
The most powerful nesting concept we will cover right now is nesting a dictionary inside of a dictionary.

To demonstrate this, let's make a dictionary of pets, with some information about each pet. The keys for this dictionary will consist of the
pet's name. The values will include information such as the kind of animal, the owner, and whether the pet has been vaccinated.

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 11/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: # This program stores information about pets. For each pet,


# we store the kind of animal, the owner's name, and
# the breed.
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True},
}

# Let's show all the information for each pet.


print("Here is what I know about Willie:")
print("kind: " + pets['willie']['kind'])
print("owner: " + pets['willie']['owner'])
print("vaccinated: " + str(pets['willie']['vaccinated']))

print("\nHere is what I know about Walter:")


print("kind: " + pets['walter']['kind'])
print("owner: " + pets['walter']['owner'])
print("vaccinated: " + str(pets['walter']['vaccinated']))

print("\nHere is what I know about Peso:")


print("kind: " + pets['peso']['kind'])
print("owner: " + pets['peso']['owner'])
print("vaccinated: " + str(pets['peso']['vaccinated']))

Clearly this is some repetitive code, but it shows exactly how we access information in a nested dictionary. In the first set of print
statements, we use the name 'willie' to unlock the 'kind' of animal he is, the 'owner' he has, and whether or not he is 'vaccinated'. We have
to wrap the vaccination value in the str function so that Python knows we want the words 'True' and 'False', not the values True and
False . We then do the same thing for each animal.

Let's rewrite this program, using a for loop to go through the dictionary's keys:

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 12/13
1/23/2021 Lecture on Dictionaries - Jupyter Notebook

In [ ]: # This program stores information about pets. For each pet,


# we store the kind of animal, the owner's name, and
# the breed.
pets = {'willie': {'kind': 'dog', 'owner': 'eric', 'vaccinated': True},
'walter': {'kind': 'cockroach', 'owner': 'eric', 'vaccinated': False},
'peso': {'kind': 'dog', 'owner': 'chloe', 'vaccinated': True},
}

# Let's show all the information for each pet.


for pet_name, pet_information in pets.items():
print("\nHere is what I know about" , pet_name.title())
print("kind: " + pet_information['kind'])
print("owner: " + pet_information['owner'])
print("vaccinated: " + str(pet_information['vaccinated']))

In [ ]:

localhost:8888/notebooks/Desktop/Python Programming Course/jup notebooks for lectures/Python lectures 2021/Lecture on Dictionaries.ipynb# 13/13

You might also like