Advanced Python - 1. Dictionaries
1.1.1 Adding New Key-Value Pairs
1.1.2 Modifying Values in a Dictionary
1.1.3 Removing Key-Value Pairs
1.2 Looping Through a Dictionary
1.2.1 Looping Through All Key-Value Pairs
1.2.2 Looping Through All Keys in a Dictionary
1.2.3 Looping Through All Values in a Dictionary
1.3.3 A Dictionary in a Dictionary
1. Dictionaries and Tuples
(fill in about data structures in general, relating to lists)
- Dictionaries allow you to connect pieces of related information.
1.1 Simple dictionaries
- A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the value associated with that key.
- A key’s value can be a number, a string, a list, or even another dictionary, or an object.
- In Python, a dictionary is wrapped in braces { }, with a series of key-value pairs inside the braces.
Example: teacher = {‘first_name’ : ‘Josh’, ‘last_name’ : ‘Finkel’}
print(teacher[first_name])
OUTPUT: Josh
- A key-value pair is a set of values associated with each other. When you provide a key, Python returns the value associated with that key. Every key is connected to its value by a colon, and individual key-value pairs are separated by commas. You can store as many key-value pairs as you want in a dictionary.
1.1.1 Adding New Key-Value Pairs
- You can add new key-value pairs to a dictionary at any time.
- To add a new piece of information to the teacher dictionary, we can do this:
Example (continued):
teacher[‘room’] = 310
print(teacher) # prints the entire dictionary
OUTPUT:
{‘first_name’ : ‘Josh’, ‘last_name’ : ‘Finkel, ‘room’ : 310}
1.1.2 Modifying Values in a Dictionary
- To change a value in a dictionary, you need to give the name of the dictionary with the key in square brackets and then the new value you want associated with that key.
Example (continued):
teacher = {‘first_name’ : ‘Joshua’} # Not Josh anymore
print(‘The teacher’s first name is ‘ + teacher[‘first_name’]
OUTPUT:
The teacher’s first name is Joshua
1.1.3 Removing Key-Value Pairs
- You can use the del statement to completely remove a key-value pair. All del needs is the name of the dictionary and the key that you want to remove.
Example (continued):
del teacher[‘last_name’]
print(teacher)
OUTPUT:
{‘first_name’ : ‘Josh’, ‘room’ : 310}
1.1.4 Formatting a Dictionary
- There is an accepted way to write a dictionary that helps to make it easier to read. In the following example, a dictionary of teachers is written in the way we have seen, and then in the clearer and more accepted way.
Example: One line
my_grades = {‘Science’ : 83, ‘English’ : 91, ‘Engineering’ : 99, ‘Art’ : 80}
Example: Better layout
my_grades = {
‘Science’ : 83,
‘English’ : 91,
‘Engineering’ : 99,
‘Art’ : 80
}
1.2 Looping Through a Dictionary
- Dictionaries can be really big. Python gives you ways to loop through all of the key-value pairs, through its keys, or through its values.
- Let’s continue with the example from the last section:
my_grades = {
‘Science’ : 83,
‘English’ : 91,
‘Engineering’ : 99,
‘Art’ : 80
}
1.2.1 Looping Through All Key-Value Pairs
- To write a for-loop for a dictionary, you create names for the two variables that will hold the key and value in each key-value pair.
- The second half of the for statement includes the name of the dictionary followed by the method items(), which returns a list of key-value pairs. (maybe show an example of what items() does)
- (run this example. The order of the output may be different)
Example:
for k, v in my_grades.items():
print(“\nKey: “ + k)
print(“Value: “ + v)
OUTPUT:
Key: Science
Value: 83
Key: English
Value: 91
Key: Engineering
Value: 99
Key: Art
Value: 80
1.2.2 Looping Through All Keys in a Dictionary
- The keys() method is useful when you don’t need to work with all of the values in a dictionary. This method returns a list of all the keys.
Example:
To get a list of just the classes in the my_grades dictionary, we could write:
for class in my_grades.keys():
print(class)
OUTPUT:
Science
English
Engineering
Art
This is actually the same as writing:
for class in my_grades: # No keys() method
print(class)
We would use the keys() method to make the code clearer.
(p105 bottom - if name in friends - might have to add this if statement to the if chapter)
- You never get the items from a dictionary in any predictable order. This isn’t usually a big deal, because you just want to get the value associated with the key.
- A way to return items in a certain order is to sort the keys as they are returned in the for loop. You can use the sort() function to get a copy of the keys in order:
Example:
print(“My classes in order:\n”)
for class in sorted(my_grades.keys()):
print(\t class)
OUTPUT: My classes in order:
Art
Engineering
English
Science
1.2.3 Looping Through All Values in a Dictionary
- You can use the values() method to return a list of values without any keys
Example: print(“List of my scores:”)
for score in my_grades.values():
print(score)
OUTPUT:
83
91
99
80
1.3 Nesting
- Dictionaries can hold lists or even other dictionaries. This is called nesting. We learned the same concept with lists of lists and with nested loops. Things inside of other things.
1.3.1 A List of Dictionaries
- Expanding on our example above, instead of having a dictionary of courses and corresponding grades, we can create a dictionary of student records.
Example:
student1 = {‘Science’ : 83, ‘English’ : 91, ‘Engineering’ : 99, ‘Art’ : 80}
student2 = {‘Math’ : 94, ‘Gym’ : 90, ‘Art’ : 88, ‘APphysics’ : 91}
student3 = {‘History’ : 83, ‘English’ : 87, ‘Math’ : 70, ‘Biology’ : 89}
students = [student1, student2, student3]
for student in students:
print(student)
OUTPUT:
{‘Science’ : 83, ‘English’ : 91, ‘Engineering’ : 99, ‘Art’ : 80}
{‘Math’ : 94, ‘Gym’ : 90, ‘Art’ : 88, ‘APphysics’ : 91}
{‘History’ : 83, ‘English’ : 87, ‘Math’ : 70, ‘Biology’ : 89}
1.3.2 Lists in a Dictionary
- We can put a list inside a dictionary. We can do this when we want more than one value to be associated with a single key in a dictionary.
Example:
- Let’s look at ordering a pizza. We could make a list of toppings, but there is more to a pizza than just toppings.
- We want to store two kinds of information for each pizza
- The type of crust
- A list of toppings
pizza = {
‘crust’: ‘thick’,
‘toppings’ : [‘mushrooms’, ‘onions’]
}
# Summarize the order
print(“You ordered a “ + pizza[‘crust’] + “-crust pizza “ +
“with the following toppings:”)
for topping in pizza[‘toppings’]:
print(“\t” + topping)
OUTPUT:
You ordered a thick-crust pizza with the following toppings:
mushrooms
onions
Example: Favorite colors
favorite_colors = {
‘jen’ : [‘purple’, ‘blue’],
‘carl’ : [‘orange’, ‘red’, ‘purple’],
‘ben’ : [‘navy blue’]
}
for name, colors in favorite_colors.items():
print(“\n” + name + “‘s favorite languages are:”
for color in colors: # Loops through color list
print(“\t” + color)
OUTPUT:
jen’s favorite colors are:
purple
blue
carl’s favorite colors are:
orange
red
purple
ben’s favorite colors are:
navy blue
1.3.3 A Dictionary in a Dictionary
- You can nest a dictionary inside another dictionary, but be careful not to make your code too complicated.
Example:
- Let’s say we want to keep track of users for a website. Each has a unique username that we can use as a key in a dictionary.
- We can then store information about each user by using a dictionary as the value associated with their username.
- Here, we store three pieces of information about each user:
- First name
- Last name
- Location
users = {
‘aeinstein’ : {
‘first’ : ‘albert’,
‘last’ : ‘einstein’,
‘location’ : ‘princeton’,
}
‘mcurie’ : {
‘first’ : ‘marie’,
‘last’ : ‘curie’,
‘location’ : ‘paris’,
}
}
for username, user_info in users.items():
print(“\nUsername: “ + username)
full_name = user_info[‘first’] + “ “ + user_info[‘last’]
location = user_info[‘location’]
print(“\tFull name: “ + full_name.title()) # title() capitalizes
print(“tLocation: “ + location.title())
OUTPUT:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
Chapter 1 Assignments
A1.1 Your First Dictionary
Use a dictionary to store information about yourself. Store your first name, last name, age and favorite movie. Print each piece of information as neatly formatted output.
A1.2 Rivers
Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be ‘nile’ : ‘egypt’. Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
A1.3 Cities
Make a dictionary of dictionaries called cities. Use the names of three cities as keys in your dictionary. Create a dictionary of information about each city and include the country that the city is in, its approximate population, and one fact about that city. The keys for each city’s dictionary should be something like country, population, and fact. Print the name of each city and all of the information you have stored about it.