← All advanced lessons

Advanced Python / A01

Dictionaries & Tuples

Creating, changing, looping through, formatting, and nesting dictionaries and tuples.

Advanced Python - 1. Dictionaries

1. Dictionaries and Tuples

1.1 Simple 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.1.4 Formatting a Dictionary

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 Nesting

1.3.1 A List of Dictionaries

1.3.2 Lists in a Dictionary

1.3.3 A Dictionary in a Dictionary

Chapter 1 Assignments

A1.1 Your First Dictionary

A1.2 Rivers

A1.3 Cities

1. Dictionaries and Tuples

(fill in about data structures in general, relating to lists)

1.1 Simple dictionaries

Example: teacher = {‘first_name’ : ‘Josh’, ‘last_name’ : ‘Finkel’}

print(teacher[first_name])

OUTPUT: Josh

1.1.1 Adding New Key-Value Pairs

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

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

Example (continued):

del teacher[‘last_name’]

print(teacher)

OUTPUT:

{‘first_name’ : ‘Josh’, ‘room’ : 310}

1.1.4 Formatting a Dictionary

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

my_grades = {

‘Science’ : 83,

‘English’ : 91,

‘Engineering’ : 99,

‘Art’ : 80

}

1.2.1 Looping Through All Key-Value Pairs

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

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)

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

Example: print(“List of my scores:”)

for score in my_grades.values():

print(score)

OUTPUT:

83

91

99

80

1.3 Nesting

1.3.1 A List of Dictionaries

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

Example:

  1. The type of crust
  2. 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

Example:

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.