<jupyter_start><jupyter_text>Working with Dictionaries A dictionary in Python is a collection of key-value pairs. Each key is connectedto 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.In fact, you can use any object that you can create in Python as a value in adictionary.In Python, a dictionary is wrapped in braces, {}, with a series of keyvaluepairs inside the braces, as shown in the earlier example:<jupyter_code>alien_0 = {'color': 'green', 'points': 5}<jupyter_output><empty_output><jupyter_text>A.  Accessing Values in a Dictionary<jupyter_code>alien_0={'color':'green'}
print(alien_0['color'])
alien_1={'color':'green','points':5}
print(alien_1['points'])
new_point=alien_1['points']
print("You just earned a point " + str(new_point))<jupyter_output>You just earned a point 5<jupyter_text>B. Adding New Key-Value Pairs<jupyter_code>alien_1['Xposition']=22
alien_1['Yposition']=56
print(alien_1)<jupyter_output>{'color': 'green', 'points': 5, 'Xposition': 22, 'Yposition': 56}<jupyter_text>C. Modifying Values in a Dictionary<jupyter_code>alien_0 = {'color': 'green','point':5}
print("The alien is " + alien_0['color'] + ".")
alien_0={'color':'Yellow'}
print("the alien is now " + alien_0['color'])
alien_0
# Exercise 1
alien_2={"Xposition": 55, "Yposition":43, "speed":"medium"}
print(" Original Position: " +str(alien_2['Xposition']))
#  Move the Alien to the right
# Determine How far the aAlien move based on its current location.
if alien_2["speed"]== "slow":
    x_increment=1
elif alien_2["speed"]== "medium":
    x_increment=5
else:
    x_increment=10
# The new position is the old position plus the increment.
alien_2["Xposition"]=alien_2["Xposition"] + x_increment 
alien_2['speed']="slkow"
alien_2["Xposition"]<jupyter_output><empty_output><jupyter_text>D. Removing Key-Value PairsWhen you no longer need a piece of information that’s stored in a dictionary,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 toremove.<jupyter_code>alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)<jupyter_output>{'color': 'green'}<jupyter_text>E.    A Dictionary of Similar ObjectsYou can also use a dictionary to store onekind of information about many objects. For example, say you want to poll anumber of people and ask them what their favorite programming languageis. A dictionary is useful for storing the results of a simple poll, like this:<jupyter_code>favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " + favorite_languages['sarah'])<jupyter_output>Sarah's favorite language is c<jupyter_text>Try It Yourself6-1. Person: 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. Youshould have keys such as first_name, last_name, age, and city. Print eachpiece of information stored in your dictionary.6-2. Favorite Numbers: Use a dictionary to store people’s favorite numbers.Think of five names, and use them as keys in your dictionary. Think of a favoritenumber for each person, and store each as a value in your dictionary. Printeach person’s name and their favorite number. For even more fun, poll a fewfriends and get some actual data for your program.6-3. Glossary: 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 previouschapters. Use these words as the keys in your glossary, and store theirmeanings as values.• Print each word and its meaning as neatly formatted output. You mightprint the word followed by a colon and then its meaning, or print the wordon one line and then print its meaning indented on a second line. Use thenewline character (\n) to insert a blank line between each word-meaningpair in your output.<jupyter_code># 6-1. Person: 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.
P_data={'first_name':" Kaleem", "last name":"ullah", "age":28, "city":"karachi", "fav_number":24}
P_data['first_name']
# 6-2. Favorite Numbers: 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.
f_data={"Kaleem":23,"gayass":28, "faraz":55,"hamza":45,"qasim":98}
       


print(f_data.items())<jupyter_output>dict_items([('Kaleem', 23), ('gayass', 28), ('faraz', 55), ('hamza', 45), ('qasim', 98)])<jupyter_text>6-3. Glossary: 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.• 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 (\n) to insert a blank line between each word-meaning pair in your output.<jupyter_code>glossary={"epoch":"no of tries",
         "wrangling":"transforming data",
         "correlation":"measure of relationship",
         "regularization":"method to avoid",
         "temporal_leak":"leak in data"}

for key, value in glossary.items():
    print(key +":\n" + value)<jupyter_output>epoch:
no of tries
wrangling:
transforming data
correlation:
measure of relationship
regularization:
method to avoid
temporal_leak:
leak in data<jupyter_text>F. Looping Through a DictionaryA single Python dictionary can contain just a few key-value pairs or millionsof pairs. Because a dictionary can contain large amounts of data, Python letsyou loop through a dictionary. Dictionaries can be used to store informationin a variety of ways; therefore, several different ways exist to loop throughthem. You can loop through all of a dictionary’s key-value pairs, through itskeys, or through its values.  i) Looping Through All Key-Value Pairs<jupyter_code>user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key,value in user_0.items():
    print("\nkey: "+ key)
    print("\nValue: "+ value)
#  method2:
for k,v in user_0.items():
    print("\nkey : "+k)
    print("value : "+ v)
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name,language in favorite_languages.items():
    print(name.title() + "'s favourite language is "+ language.title() )<jupyter_output>Jen's favourite language is Python
Sarah's favourite language is C
Edward's favourite language is Ruby
Phil's favourite language is Python<jupyter_text>ii)Looping Through All the Keys in a Dictionary<jupyter_code>favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
    print(name.title())
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends=['phil','sarah']
for name in favorite_languages.keys():
    print(name.title())
    
    if name in friends:
        print("Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title()+ ".")<jupyter_output>Jen
Sarah
Hi Sarah, I see your favorite language is C.
Edward
Phil
Hi Phil, I see your favorite language is Python.<jupyter_text>You can also use the keys() method to find out if a particular person was polled. This time, let’s find out if Erin took the poll:<jupyter_code>favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
if 'erin' not in favorite_languages.keys():
    print("Erin, please take our poll!")<jupyter_output>Erin, please take our poll!<jupyter_text>iii) Looping Through a Dictionary’s Keys in Order<jupyter_code>favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
    print(name.title() + " Thanks for taking poll")<jupyter_output>Edward Thanks for taking poll
Jen Thanks for taking poll
Phil Thanks for taking poll
Sarah Thanks for taking poll<jupyter_text>iv) Looping Through All Values in a DictionaryIf you are primarily interested in the values that a dictionary contains,you can use the values() method to return a list of values without any keys.For example, say we simply want a list of all languages chosen in our programminglanguage poll without the name of the person who chose eachlanguage:<jupyter_code>favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in favorite_languages.values():
    print(language)<jupyter_output>python
c
ruby
python<jupyter_text>This approach pulls all the values from the dictionary without checkingfor repeats. That might work fine with a small number of values, but in apoll with a large number of respondents, this would result in a very repetitivelist. To see each language chosen without repetition, we can use a set.A set is similar to a list except that each item in the set must be unique:<jupyter_code>favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in set(favorite_languages.values()):
    print(language)<jupyter_output>python
c
ruby<jupyter_text>Try It Yourself6-4. Glossary 2: Now that you know how to loop through a dictionary, cleanup the code from Exercise 6-3 (page 102) by replacing your series of printstatements 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 yourglossary. When you run your program again, these new words and meaningsshould automatically be included in the output.6-5. Rivers: Make a dictionary containing three major rivers and the countryeach 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 runsthrough Egypt.• 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.6-6. Polling: Use the code in favorite_languages.py (page 104).• Make a list of people who should take the favorite languages poll. Includesome names that are already in the dictionary and some that are not.• Loop through the list of people who should take the poll. If they havealready taken the poll, print a message thanking them for responding.If they have not yet taken the poll, print a message inviting them to takethe poll.<jupyter_code># 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) by replacing your series of print statements 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.
    
glossary={"epoch":"no of tries",
         "wrangling":"transforming data",
         "correlation":"measure of relationship",
         "regularization":"method to avoid",
         "temporal_leak":"leak in data"}
for  k,v in glossary.items():
    print(k,v)
# 6-5. 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.

# • 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.

River={"nile":"egypt","indus":"pakistan","amazon":"US"}
# • Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
for k,v in River.items():
    print("The " + k.title() + " runs  through " + v.title())
# • Use a loop to print the name of each river included in the dictionary.
for k in River.keys():
    print( k )
# • Use a loop to print the name of each country included in the dictionary.
# • Use a loop to print the name of each river included in the dictionary.
for v in River.values():
    print( v )
# 6-6. Polling: Use the code in favorite_languages.py (page 104).

# • 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.

# • 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.

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
l1=['jen', 'edward','ali']

for i in l1:
    if i in favorite_languages.keys():
        print("Thank you for taking poll" +i )
    else:
        print(i +"  you should take a poll . invited")<jupyter_output>Thank you for taking polljen
Thank you for taking polledward
ali  you should take a poll . invited<jupyter_text>G. Nesting DictionarySometimes you’ll want to store a set of dictionaries in a list or a list ofitems as a value in a dictionary. This is called nesting. You can nest a setof dictionaries inside a list, a list of items inside a dictionary, or even adictionary inside another dictionary. Nesting is a powerful feature, as thefollowing examples will demonstrate.  i) A List of DictionariesThe alien_0 dictionary contains a variety of information about one alien,but it has no room to store information about a second alien, much less ascreen full of aliens. How can you manage a fleet of aliens? One way is tomake a list of aliens in which each alien is a dictionary of information aboutthat alien. For example, the following code builds a list of three aliens:<jupyter_code>alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
    print(alien)
# Make 30 green aliens.

# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(0,30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)
for alien in aliens[0:3]:
    if alien['color']=="green":
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
for alien in aliens[0:5]:
    print(alien)<jupyter_output>{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}<jupyter_text>ii) A List in a DictionaryYou can nest a list inside a dictionary any time you want more thanone value to be associated with a single key in a dictionary.Rather than putting a dictionary inside a list, it’s sometimes useful to puta list inside a dictionary. For example, consider how you might describe apizza that someone is ordering. If you were to use only a list, all you couldreally store is a list of the pizza’s toppings. With a dictionary, a list of toppingscan be just one aspect of the pizza you’re describing.In the following example, two kinds of information are stored for eachpizza: a type of crust and a list of toppings. The list of toppings is a valueassociated with the key 'toppings'. To use the items in the list, we give thename of the dictionary and the key 'toppings', as we would any value in thedictionary. Instead of returning a single value, we get a list of toppings:<jupyter_code># Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# Summarize the order.

print(" you ordered a pizza " + pizza['crust'] + " with pizza topping")

for topping in pizza['toppings']:
    print(topping)<jupyter_output>you ordered a pizza thick with pizza topping
mushrooms
extra cheese<jupyter_text>You can nest a list inside a dictionary any time you want more thanone value to be associated with a single key in a dictionary. In the earlierexample of favorite programming languages, if we were to store eachperson’s responses in a list, people could choose more than one favoritelanguage. When we loop through the dictionary, the value associated witheach person would be a list of languages rather than a single language.Inside the dictionary’s for loop, we use another for loop to run throughthe list of languages associated with each person:<jupyter_code>favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
    print(name.title() +" fav_ language are")
    for language in languages:
        print("\t" +language)<jupyter_output>Jen fav_ language are
	python
	ruby
Sarah fav_ language are
	c
Edward fav_ language are
	ruby
	go
Phil fav_ language are
	python
	haskell<jupyter_text>-----------x-----------<jupyter_code>You should not nest lists and dictionaries too deeply. If you’re nesting items much
deeper than what you see in the preceding examples or you’re working with someone
else’s code with significant levels of nesting, most likely a simpler way to solve the
problem exists.<jupyter_output><empty_output><jupyter_text>iii) A Dictionary in a DictionaryYou can nest a dictionary inside another dictionary, but your code can getcomplicated quickly when you do. For example, if you have several usersfor a website, each with a unique username, you can use the usernames asthe keys in a dictionary. You can then store information about each user byusing a dictionary as the value associated with their username. In the followinglisting, we store three pieces of information about each user: theirfirst name, last name, and location. We’ll access this information by loopingthrough the usernames and the dictionary of information associated witheach username<jupyter_code>user={"einstine":{'first':'albert','last':'einstine','location':'princeton',},
     "mcurie":{'first':'marie','last':'curie','location':'paris'}}
for k,v in user.items():
    print("\n Username: " + k)
    fname=v['first']
    lname=v['last']
    lcation=v['location']
    print("\tFull name: " + fname.title()+lname.title())
    print("\tLocation: " + lcation.title())<jupyter_output>Username: einstine
	Full name: AlbertEinstine
	Location: Princeton

 Username: mcurie
	Full name: MarieCurie
	Location: Paris<jupyter_text>Try It Yourself6-7. People: Start with the program you wrote for Exercise 6-1 (page 102).Make two new dictionaries representing different people, and store all threedictionaries in a list called people. Loop through your list of people. As youloop through the list, print everything you know about each person.<jupyter_code>people=[{'first_name':" Kaleem", "last name":"ullah", "age":28, "city":"karachi", "fav_number":24},
    {'first_name':" khurram", "last name":"aftab", "age":24, "city":"lahore", "fav_number":1},
    {'first_name':" Abida", "last name":"imam", "age":60, "city":"islamabad", "fav_number":99}]
for p in people:
    print (p)
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the
# name of a 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=[{"name":"elephant", "kind":"mamal", "owner":"raheem"},
      {"name":"tiger", "kind":"reptial", "owner":"gayass"},
      {"name":"ant", "kind":"insect", "owner":"farukh"}]
for v in pets:
    print(v)
# 6-9. Favorite Places: 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 place.

favorite_places={"ali":['phuket','jeddah'],
                 "qasim":['islambad'],
                 "malik":['toronto','melbourne', 'singapore']}
for k,v in favorite_places.items():
    print(k,v)
for places in favorite_places['malik']:
    print(places)
6-10. Favorite Numbers: Modify your program from Exercise 6-2 (page 102) so
each person can have more than one favorite number. Then print each person’s
name along with their favorite numbers.
6-11. Cities: 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. Print the name of each city and all of the information
you have stored about it.
6-12. Extensions: 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.<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0980149452161555, 'fraction_numerical': 0.008756246275157016, 'mean_word_length': 4.868711326338445, 'pattern_counts': {'":': 55, '<': 68, '<?xml version=': 0, '>': 68, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '21', 'dir': 'jupyter-structured-clean-dedup', 'id': '233248', 'license': 'MIT', 'n_tokens_mistral': 6511, 'n_tokens_neox': 6211, 'n_words': 2917, 'path': 'DICTIONARY.ipynb', 'repo_name': 'wahmed555/PyPractice', 'size': '21813'}