= {'first_name': 'qaisar',
person 'last_name': 'abbas',
'age': 34,
'city':'lahore',
}
'first_name']
person['last_name'] person[
'abbas'
Use a dictionary to store information about a person you know. Store their first name, last name, age, and the city in which they live. You should have keys such as first_name, last_name, age, and city. Print each piece of information stored in your dictionary.
Use a dictionary to store people’s favorite numbers. Think of five names, and use them as keys in your dictionary. Think of a favorite number for each person, and store each as a value in your dictionary. Print each person’s name and their favorite number. For even more fun, poll a few friends and get some actual data for your program.
A Python dictionary can be used to model an actual dictionary. However, to avoid confusion, let’s call it a glossary.
Think of five programming words you’ve learned about in the previous chapters. Use these words as the keys in your glossary, and store their meanings as values.
glossary = {'if':'if statement has a else and elif parts for conditional running of code',
'for':'for loop is used get the value from a list repeatedly',
'else':'else statement is a oart of if-else conditional statements',
'variable':'Variable can be int, float or string',
}
glossary['variable']
'Variable can be int, float or string'
Print each word and its meaning as neatly formatted output. You might print the word followed by a colon and then its meaning, or print the word on one line and then print its meaning indented on a second line. Use the newline character () to insert a blank line between each word-meaning pair in your output.
Key: if
Value: if statement has a else and elif parts for conditional running of code
Key: for
Value: for loop is used get the value from a list repeatedly
Key: else
Value: else statement is a oart of if-else conditional statements
Key: variable
Value: Variable can be int, float or string
getting only keys
statements = ['for','else']
for name in glossary.keys():
print(f"Hello {name.title()}")
if name in statements:
definition = glossary[name].title()
print(f"I see this stands for {definition}")
Hello If
Hello For
I see this stands for For Loop Is Used Get The Value From A List Repeatedly
Hello Else
I see this stands for Else Statement Is A Oart Of If-Else Conditional Statements
Hello Variable
Using sorted for all keys in glossary dictionary
Please check this: else
Please check this: for
Please check this: if
Please check this: variable
To get values
print("We have defined Python important terms as:\n")
for name in sorted(glossary.values()):
print(f"{name.title()}")
We have defined Python important terms as:
Variable Can Be Int, Float Or String
Else Statement Is A Oart Of If-Else Conditional Statements
For Loop Is Used Get The Value From A List Repeatedly
If Statement Has A Else And Elif Parts For Conditional Running Of Code
Using set
Since we already do not have repititive values the set function will not serve the purpose we want.
Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 99) by replacing your series of print() calls with a loop that runs through the dictionary’s keys and values. When you’re sure that your loop works, add five more Python terms to your glossary. When you run your program again, these new words and meanings should automatically be included in the output.
Already done in practice code above
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.
for name in set(rivers.keys()):
for middle in set(rivers.values()):
print(f"The {name.title()} runs through {middle.title()}")
The Sindh runs through Egypt
The Sindh runs through Pakistan
The Sindh runs through France
The Nile runs through Egypt
The Nile runs through Pakistan
The Nile runs through France
The Isere runs through Egypt
The Isere runs through Pakistan
The Isere runs through France
Use a loop to print the name of each river included in the dictionary.
Use a loop to print the name of each country included in the dictionary.
Use the code in favorite_languages.py (page 96).
Make a list of people who should take the favorite languages poll. Include some names that are already in the dictionary and some that are not.
Code already given above for glossary dictionary
Loop through the list of people who should take the poll. If they have already taken the poll, print a message thanking them for responding. If they have not yet taken the poll, print a message inviting them to take the poll.
# taking code from book page # 96
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
people_for_poll = ['jen','sarah']
people_not_poll = ['edward','phil']
for name in favorite_languages.keys():
if name in people_for_poll:
print(f"Hello {name}, Thanks for poll")
elif name in people_not_poll:
print(f"Hello {name}, Please take the poll")
Hello jen, Thanks for poll
Hello sarah, Thanks for poll
Hello edward, Please take the poll
Hello phil, Please take the poll
favorite_languages = {
'jen': ['python', 'rust'],
'sarah': ['c'],
'edward': ['rust', 'go'],
'phil': ['python', 'haskell'],
}
for name,lang in favorite_languages.items():
print(f"Hey {name},")
for l in lang:
print(f" You like the {l}")
Hey jen,
You like the python
You like the rust
Hey sarah,
You like the c
Hey edward,
You like the rust
You like the go
Hey phil,
You like the python
You like the haskell
Start with the program you wrote for Exercise 6-1 (page 98). Make two new dictionaries representing different people, and store all three dictionaries in a list called people. Loop through your list of people. As you loop through the list, print everything you know about each person.
person = {'first_name': 'qaisar',
'last_name': 'abbas',
'age': 34,
'city':'lahore',
}
person1 = {'first_name':'amir',
'last_name':'abbas',
'age':32,
'city':'chiniot'}
person2 = {'first_name':'jabir',
'last_name':'abbas',
'age':26,
'city':'chiniot'}
people = [person,person1,person2]
for individual in people:
for i,j in individual.items():
print(f"He is a person with {i}={j}")
He is a person with first_name=qaisar
He is a person with last_name=abbas
He is a person with age=34
He is a person with city=lahore
He is a person with first_name=amir
He is a person with last_name=abbas
He is a person with age=32
He is a person with city=chiniot
He is a person with first_name=jabir
He is a person with last_name=abbas
He is a person with age=26
He is a person with city=chiniot
for individual in people:
sentence = " ".join([f"{k}={v}" for k, v in individual.items()])
print(f"He is a person with {sentence}")
He is a person with first_name=qaisar last_name=abbas age=34 city=lahore
He is a person with first_name=amir last_name=abbas age=32 city=chiniot
He is a person with first_name=jabir last_name=abbas age=26 city=chiniot
Make several dictionaries, where each dictionary represents a different pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do, print everything you know about each pet.
pets = [{'dog':'4 legs',
'owner':'amir',
},
{'cat':'4 legs',
'owner':'qaisar',
},
{'hen':'2 legs',
'owner':'jabir',
}]
for individual in pets:
for animal,legs in individual.items():
if animal != 'owner':
print(f"Animal is {animal.title()}, it has {legs} and it's owner is ",end="")
elif legs != '4 legs' or '2 legs':
print(f"{legs.title()}")
Animal is Dog, it has 4 legs and it's owner is Amir
Animal is Cat, it has 4 legs and it's owner is Qaisar
Animal is Hen, it has 2 legs and it's owner is Jabir
Make a dictionary called favorite_places. Think of three names to use as keys in the dictionary, and store one to three favorite places for each person. To make this exercise a bit more interesting, ask some friends to name a few of their favorite places. Loop through the dictionary, and print each person’s name and their favorite places.
favorite_places = {'qaisar':['makka','madina'],
'amir':['damascus','baghdad'],
'jabir':['basra','al-quds']
}
for individual,places in favorite_places.items():
print(f"Favorite places of {individual} are {' and '.join(places)}")
Favorite places of qaisar are makka and madina
Favorite places of amir are damascus and baghdad
Favorite places of jabir are basra and al-quds
Modify your program from Exercise 6-2 (page 98) so each person can have more than one favorite number. Then print each person’s name along with their favorite numbers.
numbers = {'qaisar': [34,48],
'kainat': [23,31],
'amna': [29,76]
}
for individual,places in numbers.items():
print(f"Favorite numbers of {individual} are {' and '.join(str(i) for i in places)}")
Favorite numbers of qaisar are 34 and 48
Favorite numbers of kainat are 23 and 31
Favorite numbers of amna are 29 and 76
Make a dictionary 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.
# we take different route instead of putting fact and population
cities = {
'grenoble':{'popular food': 'cheese',
'tourist attraction': 'ski stations',
'rivers' : 'isere',
'country':'france'},
'dejon': {'popular food': 'baggette',
'tourist attraction': 'fields',
'rivers' : 'loire',
'country':'france'},
'annancy': {'popular food': 'fish',
'tourist attraction': 'annancy lake',
'rivers' : 'annancy river',
'country':'france'}
}
Print the name of each city and all of the information you have stored about it.
for city,info in cities.items():
food = info['popular food']
tour = info['tourist attraction']
river = info['rivers']
country = info['country']
print(f"City {city} is located in {country.title()}. It has popular food of {food}, tourist attraction of {tour} and a popular river named {river.title()}.","\n")
City grenoble is located in France. It has popular food of cheese, tourist attraction of ski stations and a popular river named Isere.
City dejon is located in France. It has popular food of baggette, tourist attraction of fields and a popular river named Loire.
City annancy is located in France. It has popular food of fish, tourist attraction of annancy lake and a popular river named Annancy River.
We’re now working with examples that are complex enough that they can be extended in any number of ways. Use one of the example programs from this chapter, and extend it by adding new keys and values, changing the context of the program, or improving the formatting of the output.
Already given above
End of Chapter 6