Python Dictionaries Lab Manual
Contents
1 Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Lab Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
3 Introduction to Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4 Lab Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4.1 Exercise 10-1: Person . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
4.2 Exercise 10-2: Favorite Numbers . . . . . . . . . . . . . . . . . . . . . . . 3
4.3 Exercise 10-3: Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.4 Exercise 10-4: Glossary 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.5 Exercise 10-5: Rivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.6 Exercise 10-10: Polling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.7 Exercise 10-7: People . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.8 Exercise 10-8: Pets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.9 Exercise 10-9: Favorite Places . . . . . . . . . . . . . . . . . . . . . . . . 11
4.10 Exercise 10-10: Favorite Numbers (Extended) . . . . . . . . . . . . . . . 12
4.11 Exercise 10-11: Cities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.12 Exercise 10-12: Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5 Additional Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
6 Submission Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1
1 Objective
This lab introduces Python dictionaries, a powerful data structure for storing and manip-
ulating key-value pairs. You will learn how to create, access, modify, and loop through
dictionaries, as well as how to nest dictionaries and lists. By completing the exercises,
you will gain hands-on experience in using dictionaries to model real-world data.
2 Lab Setup
• Environment: Python 3.7 or later
• Editor: Any Python IDE (e.g., PyCharm, VS Code, IDLE) or a text editor with
a Python interpreter
• Files: Save each exercise as a separate .py file (e.g., exercise 10 1.py)
• Prerequisites: Basic understanding of Python variables, lists, and loops
3 Introduction to Dictionaries
A dictionary in Python is a collection of key-value pairs wrapped in curly braces {}.
Each key is unique and maps to a specific value, which can be a number, string, list, or
another dictionary. Dictionaries are dynamic, allowing you to add, modify, or remove
key-value pairs.
alien_0 = { ’ color ’: ’ green ’ , ’ points ’: 5}
print ( alien_0 [ ’ color ’ ]) # Output : green
print ( alien_0 [ ’ points ’ ]) # Output : 5
In this example, alien 0 is a dictionary with two keys (color and points) and their
corresponding values (’green’ and 5). You access values using square brackets [] with
the key.
4 Lab Exercises
4.1 Exercise 10-1: Person
Objective: Create a dictionary to store information about a person and print each piece
of information.
Instructions:
1. Create a dictionary called person with keys first name, last name, age, and city.
2. Assign appropriate values to each key (e.g., your own or a friend’s details).
3. Print each piece of information stored in the dictionary.
Code:
2
# exercise_10_1 . py
person = {
’ first_name ’: ’ John ’ ,
’ last_name ’: ’ Doe ’ ,
’ age ’: 30 ,
’ city ’: ’ New York ’
}
print ( f " First Name : { person [ ’ first_name ’]} " )
print ( f " Last Name : { person [ ’ last_name ’]} " )
print ( f " Age : { person [ ’ age ’]} " )
print ( f " City : { person [ ’ city ’]} " )
Explanation:
• The dictionary person stores four key-value pairs.
• Each value is accessed using the dictionary name and the key in square brackets
(e.g., person[’first name’]).
• The print() statements use f-strings to format and display each piece of informa-
tion.
Expected Output:
First Name: John
Last Name: Doe
Age: 30
City: New York
4.2 Exercise 10-2: Favorite Numbers
Objective: Create a dictionary to store people’s favorite numbers and print them.
Instructions:
1. Create a dictionary called favorite numbers with five names as keys and a favorite
number for each person as the value.
2. Print each person’s name and their favorite number.
Code:
# exercise_10_2 . py
favorite_numbers = {
’ alice ’: 7 ,
’ bob ’: 42 ,
’ charlie ’: 19 ,
’ diana ’: 3 ,
’ eve ’: 25
}
for name , number in favorite_numbers . items () :
print ( f " { name . title () } ’ s favorite number is { number }. " )
3
Explanation:
• The dictionary favorite numbers maps names (keys) to numbers (values).
• The items() method is used to loop through both keys and values, assigning them
to name and number.
• The title() method capitalizes the first letter of each name for cleaner output.
Expected Output:
Alice’s favorite number is 7.
Bob’s favorite number is 42.
Charlie’s favorite number is 19.
Diana’s favorite number is 3.
Eve’s favorite number is 25.
4.3 Exercise 10-3: Glossary
Objective: Create a glossary of programming terms and their meanings, printing them
in a formatted manner.
Instructions:
1. Create a dictionary called glossary with five programming terms as keys and their
meanings as values.
2. Print each term and its meaning with a blank line between each pair.
Code:
# exercise_10_3 . py
glossary = {
’ variable ’: ’A named storage location in memory . ’ ,
’ list ’: ’A collection of ordered , mutable items . ’ ,
’ loop ’: ’A control structure to repeat code execution . ’ ,
’ function ’: ’A reusable block of code performing a specific
task . ’ ,
’ string ’: ’A sequence of characters . ’
}
for term , meaning in glossary . items () :
print ( f " { term . title () }:\ n \ t { meaning }\ n " )
Explanation:
• The glossary dictionary maps programming terms to their definitions.
• The items() method allows looping through key-value pairs.
• The print() statement uses \n for a blank line and \t for indentation to format
the output neatly.
Expected Output:
Variable:
4
A named storage location in memory.
List:
A collection of ordered, mutable items.
Loop:
A control structure to repeat code execution.
Function:
A reusable block of code performing a specific task.
String:
A sequence of characters.
4.4 Exercise 10-4: Glossary 2
Objective: Improve Exercise 10-3 by using a loop and adding more terms.
Instructions:
1. Start with the glossary dictionary from Exercise 10-3.
2. Replace individual print() calls with a loop.
3. Add five more programming terms and their meanings.
4. Print all terms and meanings with the same formatting.
Code:
# exercise_10_4 . py
glossary = {
’ variable ’: ’A named storage location in memory . ’ ,
’ list ’: ’A collection of ordered , mutable items . ’ ,
’ loop ’: ’A control structure to repeat code execution . ’ ,
’ function ’: ’A reusable block of code performing a specific
task . ’ ,
’ string ’: ’A sequence of characters . ’ ,
’ dictionary ’: ’A collection of key - value pairs . ’ ,
’ tuple ’: ’ An immutable sequence of items . ’ ,
’ boolean ’: ’A data type with True or False values . ’ ,
’ module ’: ’A file containing Python code for reuse . ’ ,
’ exception ’: ’ An error that occurs during program execution . ’
}
for term , meaning in glossary . items () :
print ( f " { term . title () }:\ n \ t { meaning }\ n " )
Explanation:
• The dictionary is expanded with five additional terms: dictionary, tuple, boolean,
module, and exception.
5
• The loop structure remains the same as in Exercise 10-3, ensuring all terms are
printed with consistent formatting.
• The use of items() allows efficient iteration over the dictionary.
Expected Output:
Variable:
A named storage location in memory.
List:
A collection of ordered, mutable items.
Loop:
A control structure to repeat code execution.
Function:
A reusable block of code performing a specific task.
String:
A sequence of characters.
Dictionary:
A collection of key-value pairs.
Tuple:
An immutable sequence of items.
Boolean:
A data type with True or False values.
Module:
A file containing Python code for reuse.
Exception:
An error that occurs during program execution.
4.5 Exercise 10-5: Rivers
Objective: Create a dictionary of rivers and their countries, and print information using
loops.
Instructions:
1. Create a dictionary called rivers with three rivers as keys and their countries as
values.
2. Use a loop to print a sentence about each river.
3. Use a loop to print the name of each river.
4. Use a loop to print the name of each country.
6
Code:
# exercise_10_5 . py
rivers = {
’ nile ’: ’ egypt ’ ,
’ amazon ’: ’ brazil ’ ,
’ yangtze ’: ’ china ’
}
# Print a sentence about each river
for river , country in rivers . items () :
print ( f " The { river . title () } runs through { country . title () }. " )
# Print the name of each river
print ( " \ nRivers : " )
for river in rivers . keys () :
print ( river . title () )
# Print the name of each country
print ( " \ nCountries : " )
for country in rivers . values () :
print ( country . title () )
Explanation:
• The rivers dictionary maps river names to their countries.
• The first loop uses items() to access both keys and values, printing a sentence for
each river.
• The second loop uses keys() to print only the river names.
• The third loop uses values() to print only the country names.
• The title() method ensures proper capitalization.
Expected Output:
The Nile runs through Egypt.
The Amazon runs through Brazil.
The Yangtze runs through China.
Rivers:
Nile
Amazon
Yangtze
Countries:
Egypt
Brazil
China
7
4.6 Exercise 10-10: Polling
Objective: Check a list of people against a favorite languages dictionary and print
appropriate messages.
Instructions:
1. Use the favorite languages dictionary from the chapter.
2. Create a list of people who should take the poll, including some names in the
dictionary and some not.
3. Loop through the list, thanking those who have taken the poll and inviting others
to participate.
Code:
# exercise_10_10 . py
favorite_l an gu ag es = {
’ jen ’: ’ python ’ ,
’ sarah ’: ’c ’ ,
’ edward ’: ’ ruby ’ ,
’ phil ’: ’ python ’
}
people = [ ’ jen ’ , ’ sarah ’ , ’ alice ’ , ’ bob ’ , ’ phil ’]
for person in people :
if person in f av or it e_ la ng ua ge s . keys () :
print ( f " { person . title () } , thank you for taking the poll ! "
)
else :
print ( f " { person . title () } , please take our poll ! " )
Explanation:
• The favorite languages dictionary contains names and their favorite program-
ming languages.
• The people list includes names, some of which are in the dictionary (jen, sarah,
phil) and some not (alice, bob).
• The loop checks if each person is in the dictionary using keys(). If they are, a
thank-you message is printed; otherwise, an invitation is printed.
Expected Output:
Jen, thank you for taking the poll!
Sarah, thank you for taking the poll!
Alice, please take our poll!
Bob, please take our poll!
Phil, thank you for taking the poll!
8
4.7 Exercise 10-7: People
Objective: Store multiple people’s information in dictionaries and print them using a
list.
Instructions:
1. Start with the person dictionary from Exercise 10-1.
2. Create two new dictionaries for different people.
3. Store all three dictionaries in a list called people.
4. Loop through the list and print all information about each person.
Code:
# exercise_10_7 . py
person_1 = {
’ first_name ’: ’ John ’ ,
’ last_name ’: ’ Doe ’ ,
’ age ’: 30 ,
’ city ’: ’ New York ’
}
person_2 = {
’ first_name ’: ’ Jane ’ ,
’ last_name ’: ’ Smith ’ ,
’ age ’: 25 ,
’ city ’: ’ Los Angeles ’
}
person_3 = {
’ first_name ’: ’ Alice ’ ,
’ last_name ’: ’ Johnson ’ ,
’ age ’: 28 ,
’ city ’: ’ Chicago ’
}
people = [ person_1 , person_2 , person_3 ]
for person in people :
print ( f " \ nName : { person [ ’ first_name ’]. title () } { person [ ’
last_name ’]. title () } " )
print ( f " Age : { person [ ’ age ’]} " )
print ( f " City : { person [ ’ city ’]. title () } " )
Explanation:
• Three dictionaries (e.g., person 1, person 2, person 3) store information about
different people.
• These dictionaries are stored in a list called people.
• The loop iterates through the people list, accessing each dictionary and printing
its key-value pairs in a formatted manner.
Expected Output:
9
Name: John Doe
Age: 30
City: New York
Name: Jane Smith
Age: 25
City: Los Angeles
Name: Alice Johnson
Age: 28
City: Chicago
4.8 Exercise 10-8: Pets
Objective: Create dictionaries for pets, store them in a list, and print their information.
Instructions:
1. Create several dictionaries, each representing a pet with keys for the kind of animal
and the owner’s name.
2. Store the dictionaries in a list called pets.
3. Loop through the list and print all information about each pet.
Code:
# exercise_10_8 . py
pet_1 = { ’ kind ’: ’ dog ’ , ’ owner ’: ’ Alice ’}
pet_2 = { ’ kind ’: ’ cat ’ , ’ owner ’: ’ Bob ’}
pet_3 = { ’ kind ’: ’ parrot ’ , ’ owner ’: ’ Charlie ’}
pets = [ pet_1 , pet_2 , pet_3 ]
for pet in pets :
print ( f " \ nPet : { pet [ ’ kind ’]. title () } " )
print ( f " Owner : { pet [ ’ owner ’]. title () } " )
Explanation:
• Each dictionary (e.g., pet 1, pet 2, pet 3) contains two keys: kind (type of animal)
and owner (owner’s name).
• The pets list stores all pet dictionaries.
• The loop iterates through the pets list, printing each pet’s kind and owner in a
formatted manner.
Expected Output:
Pet: Dog
Owner: Alice
Pet: Cat
10
Owner: Bob
Pet: Parrot
Owner: Charlie
4.9 Exercise 10-9: Favorite Places
Objective: Create a dictionary of people’s favorite places and print them.
Instructions:
1. Create a dictionary called favorite places with three names as keys and a list of
one to three favorite places as values.
2. Loop through the dictionary and print each person’s name and their favorite places.
Code:
# exercise_10_9 . py
favorite_places = {
’ alice ’: [ ’ paris ’ , ’ new york ’ , ’ tokyo ’] ,
’ bob ’: [ ’ london ’ , ’ sydney ’] ,
’ charlie ’: [ ’ rome ’]
}
for name , places in favorite_places . items () :
print ( f " \ n { name . title () } ’ s favorite places are : " )
for place in places :
print ( f " \ t { place . title () } " )
Explanation:
• The favorite places dictionary maps names to lists of favorite places.
• The outer loop uses items() to access each name and their list of places.
• The inner loop iterates through the list of places for each person, printing them
with indentation.
Expected Output:
Alice’s favorite places are:
Paris
New York
Tokyo
Bob’s favorite places are:
London
Sydney
Charlie’s favorite places are:
Rome
11
4.10 Exercise 10-10: Favorite Numbers (Extended)
Objective: Modify Exercise 10-2 to allow multiple favorite numbers per person.
Instructions:
1. Modify the favorite numbers dictionary from Exercise 10-2 so each person has a
list of favorite numbers.
2. Print each person’s name and their favorite numbers.
Code:
# exercise_10_10 . py
favorite_numbers = {
’ alice ’: [7 , 14 , 21] ,
’ bob ’: [42 , 99] ,
’ charlie ’: [19] ,
’ diana ’: [3 , 10 , 9] ,
’ eve ’: [25 , 50]
}
for name , numbers in favorite_numbers . items () :
print ( f " \ n { name . title () } ’ s favorite numbers are : " )
for number in numbers :
print ( f " \ t { number } " )
Explanation:
• The favorite numbers dictionary now maps names to lists of numbers.
• The outer loop uses items() to access each name and their list of numbers.
• The inner loop iterates through the list of numbers, printing them with indentation.
Expected Output:
Alice’s favorite numbers are:
7
14
21
Bob’s favorite numbers are:
42
99
Charlie’s favorite numbers are:
19
Diana’s favorite numbers are:
3
10
9
12
Eve’s favorite numbers are:
25
50
4.11 Exercise 10-11: Cities
Objective: Create a dictionary of cities with nested dictionaries containing city infor-
mation.
Instructions:
1. Create a dictionary called cities with three city names as keys.
2. For each city, create a nested dictionary with keys country, population, and fact.
3. Print each city’s name and its information.
Code:
# exercise_10_11 . py
cities = {
’ tokyo ’: {
’ country ’: ’ japan ’ ,
’ population ’: 374000108 ,
’ fact ’: ’ Tokyo is the largest metropolitan area in the
world . ’
},
’ new york ’: {
’ country ’: ’ united states ’ ,
’ population ’: 83310817 ,
’ fact ’: ’ New York City is known as the Big Apple . ’
},
’ london ’: {
’ country ’: ’ united kingdom ’ ,
’ population ’: 89822510 ,
’ fact ’: ’ London has one of the oldest underground railway
systems . ’
}
}
for city , info in cities . items () :
print ( f " \ nCity : { city . title () } " )
print ( f " Country : { info [ ’ country ’]. title () } " )
print ( f " Population : { info [ ’ population ’]: ,} " )
print ( f " Fact : { info [ ’ fact ’]} " )
Explanation:
• The cities dictionary uses city names as keys, with each value being a nested
dictionary containing country, population, and fact.
• The loop uses items() to access each city and its nested dictionary (info).
13
• The nested dictionary’s keys are used to print the country, population (formatted
with commas), and fact.
Expected Output:
City: Tokyo
Country: Japan
Population: 37,400,0108
Fact: Tokyo is the largest metropolitan area in the world.
City: New York
Country: United States
Population: 8,3310,817
Fact: New York City is known as the Big Apple.
City: London
Country: United Kingdom
Population: 8,982,2510
Fact: London has one of the oldest underground railway systems.
4.12 Exercise 10-12: Extensions
Objective: Extend an existing program by adding new features and improving format-
ting.
Instructions:
1. Extend the favorite languages program to include additional information (e.g.,
years of experience with each language).
2. Modify the output to display whether each person has one or multiple favorite
languages.
3. Sort the names alphabetically before printing.
Code:
# exercise_10_12 . py
favorite_l an gu ag es = {
’ jen ’: { ’ languages ’: [ ’ python ’ , ’ ruby ’] , ’ experience ’: [5 ,
2]} ,
’ sarah ’: { ’ languages ’: [ ’c ’] , ’ experience ’: [3]} ,
’ edward ’: { ’ languages ’: [ ’ ruby ’ , ’ go ’] , ’ experience ’: [4 ,
1]} ,
’ phil ’: { ’ languages ’: [ ’ python ’ , ’ haskell ’] , ’ experience ’:
[10 , 3]}
}
for name in sorted ( fa vo ri te _l ang ua ge s . keys () ) :
info = fav or it e_ la ng ua ge s [ name ]
languages = info [ ’ languages ’]
experience = info [ ’ experience ’]
lang_count = len ( languages )
14
print ( f " \ n { name . title () } ’ s favorite language { ’ s ’ if
lang_count > 1 else ’ ’} { ’ are ’ if lang_count > 1 else ’ is
’}: " )
for i , language in enumerate ( languages ) :
print ( f " \ t { language . title () } ({ experience [ i ]} years ) " )
Explanation:
• The favorite languages dictionary now uses nested dictionaries, with each person
having a languages list and an experience list for years of experience.
• The sorted() function sorts the keys (names) alphabetically.
• The loop checks the number of languages (lang count) to adjust the wording (“lan-
guage” vs. “languages”, “is” vs. “are”).
• The inner loop uses enumerate() to pair each language with its corresponding
experience value.
Expected Output:
Edward’s favorite languages are:
Ruby (4 years)
Go (1 years)
Jen’s favorite languages are:
Python (5 years)
Ruby (2 years)
Phil’s favorite languages are:
Python (10 years)
Haskell (3 years)
Sarah’s favorite language is:
C (3 years)
5 Additional Notes
• Error Handling with get(): Use the get() method to avoid KeyError when
accessing keys that may not exist. Example: alien 0.get(’points’, ’No points
assigned’) returns a default value if the key is missing.
• Dictionary Order: As of Python 3.7, dictionaries maintain insertion order, en-
suring consistent output when looping.
• Nesting: Be cautious with deep nesting, as it can complicate code. Consider
alternative data structures if nesting becomes too complex.
• Sets for Unique Values: Use set(favorite languages.values()) to extract
unique values from a dictionary, as shown in the chapter.
15
6 Submission Instructions
1. Save each exercise as a separate .py file (e.g., exercise 10 1.py).
2. Test each program to ensure it produces the expected output.
3. Submit all files along with a brief report summarizing what you learned about
dictionaries.
16