<jupyter_start><jupyter_text>Exercicies > Here you will see:>>* How to access and modify individual elements in a dictionary.>>* How to loop through all of the information in a dictionary. >>>* How to loop through a dictionary’s:>>>>__key-value pairs__, >>>>__its keys__, >>>>__and its values__. >> Nesting multiple __dictionaries in a list, nest lists in a dictionary, and nest a dictionary insidea dictionary__.>>> And also how to access each information of the list and dictionaries nested in each other through a loop.I took this exercises from the book __"Python Crash A Hands_on to Programming"__.<jupyter_code>alien_0={"color":"green","points":5}

print(alien_0 ["color"])
print(alien_0 ["points"])
new_points = alien_0["points"]
print(f"You just earned {new_points} points!")
print(alien_0)
alien_0["x_position"]=0
alien_0["y_position"]=25
print(alien_0)
#starting with a empty dictionary

alien_0={}
    
alien_0["color"]='green'
alien_0["points"]=5

print(alien_0)

alien_0  = {"color":"green"}
print(f"The Alien is {alien_0['color']}.")

alien_0["color"]="yellow"
print(f"The Alien is now {alien_0['color']}.")


alien_0={'x_position':0, 'y_position':25,'speed':'medium'}
print(f"Original position: {alien_0['x_position']}.")

#Move the alien to the right
#Determine how far to move  the alien on its current speed.

if alien_0['speed']=='slow':
    x_increment=1
elif alien_0['speed']=="medium":
    x_increment=2
else:
    # This must be a fast alien
    x_increment=3
    
    
# The new position is the old position plus the increment

alien_0['x_position']=alien_0['x_position']+x_increment

print(f"New position: {alien_0['x_position']}.")
alien_0={'x_position':0, 'y_position':25,'speed':'medium'}
alien_0['speed']="fast"
print(f"Original position: {alien_0['x_position']}.")

#Move the alien to the right
#Determine how far to move  the alien on its current speed.

if alien_0['speed']=='slow':
    x_increment=1
elif alien_0['speed']=="medium":
    x_increment=2
else:
    # This must be a fast alien
    x_increment=3
    
    
# The new position is the old position plus the increment

alien_0['x_position']=alien_0['x_position']+x_increment

print(f"New position: {alien_0['x_position']}.")<jupyter_output>Original position: 0.
New position: 3.<jupyter_text>we stopped at the page 96 removing Key_Value Pairs Removing Key value pairs<jupyter_code>alien_0={'color':"green",'points':5}
print(alien_0)

del alien_0 ['points']
print(alien_0)<jupyter_output>{'color': 'green', 'points': 5}
{'color': 'green'}<jupyter_text>A Dictionary of similar objects<jupyter_code>favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
language=favorite_languages['sarah'].title()
print(f"Sara's favorite language is {language}.")<jupyter_output>Sara's favorite language is C.<jupyter_text>Using Get() to access values<jupyter_code>alien_0={'color':'green','speed':'slow'}
print(alien_0['points'])
alien_0={'color':'green','speed':'slow'}


point_value=alien_0.get('points','No point value assined.')
print(point_value)<jupyter_output>No point value assined.<jupyter_text>Try it yourself __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.<jupyter_code>Guilherme_information ={"first_name":"Guilherme","last_name":"Thomazelli","age":39,"city":"sao paulo"}

print(f"His first name is {Guilherme_information['first_name'].upper()}")
      
print(Guilherme_information['last_name'])
print(Guilherme_information['age'])
print(Guilherme_information['city'])<jupyter_output>His first name is GUILHERME
Thomazelli
39
sao paulo<jupyter_text>__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.<jupyter_code>friends_numbers={'sara':1,"john":2,"israel":3}
print("My friend Sara likes the number {friends_numbers['sara']}.")
friends_numbers['sara']=5
print(f"Sara changed her favorite number to{friends_numbers['sara']}.")<jupyter_output>My friend Sara likes the number {friends_numbers['sara']}.
Sara changed her favorite number to5.<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={
    'darg':"day of work",
    'polyglot':"a person who speaks, writes, or reads a number of languages.",
    'frumious':"very angry.",
    'zeugma':"he use of a word to modify or govern two or more words when\
    it is appropriate to only one of them or is appropriate to each but in a \
    different way, as in On his fishing trip, he caught three trout and a cold.",
    'decussate':'to cross in the form of an X; intersect.',

}



for k,v in glossary.items():
    print(f"Word the day {k.upper()} meanings:\n{v.title()}. \n")<jupyter_output>Word the day DARG meanings:
Day Of Work. 

Word the day POLYGLOT meanings:
A Person Who Speaks, Writes, Or Reads A Number Of Languages.. 

Word the day FRUMIOUS meanings:
Very Angry.. 

Word the day ZEUGMA meanings:
He Use Of A Word To Modify Or Govern Two Or More Words When    It Is Appropriate To Only One Of Them Or Is Appropriate To Each But In A     Different Way, As In On His Fishing Trip, He Caught Three Trout And A Cold.. 

Word the day DECUSSATE meanings:
To Cross In The Form Of An X; Intersect..<jupyter_text>Looping thought all Key_Values Pairs<jupyter_code>user_0={
    'username':'efermi',
    'first':'enrico',
    'last':'fermi',
}

for Key, Value in user_0.items():
    print(f"\nKey {Key}")
    print(f"Value {Value}")
favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

for name, language in favorite_languages.items():
    print(f"{name.title()}'s favorite languague is {language.upper()}.")<jupyter_output>Jen's favorite languague is PYTHON.
Sarah's favorite languague is C.
Edward's favorite languague is RUBY.
Phil's favorite languague is PYTHON.<jupyter_text>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())
# I also couls simplify it with taking out the Key because this is the default behavior of a dictionary:

favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name in favorite_languages:
    print(name.title())
friends=['phil','sarah']
for name in favorite_languages.keys():
    print(name.title())
    
    if name in friends:
        language=favorite_languages[name].title()
        print(f"\t{name.title()},I see you love {language}!")
if 'erin' not in favorite_languages.keys():
    print(f" Erin, please take out poll!")<jupyter_output>Erin, please take out poll!<jupyter_text>Looping through a Dictionary's Key in a Particular Order<jupyter_code>favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

for name in sorted(favorite_languages.keys()):
    print(f"{name.title()}, thank you for taking the poll.")
favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

print("The following languages have been mentioned:")
for language in sorted(favorite_languages.values()):
    print(language.title())
# Let's use a set. A set is a collection in which each item is unique.

favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())
#set
#As you continue learning about Python, you’ll often find a built-in fea-
#ture of the language that helps you do exactly what you want with your data.


#It’s easy to mistake sets for dictionaries because they’re both wrapped in braces.
#When you see braces but no key-value pairs, you’re probably looking at a set. Unlike
#lists and dictionaries, sets do not retain items in any specific order.
#Note You can build a set directly using braces and separating the elements with commas:

language={'python',"C","ruby"}
language<jupyter_output><empty_output><jupyter_text>__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.<jupyter_code>rivers={"amazon":"brazil","yangtze":"china","mississippi":"united states","yenisei":"russia"}
for river, country in rivers.items():
    print(f"The {river.title()} runs {country.title()}.")

for river in rivers.keys():
    print(river.title())
for country in rivers.values():
    print(country.title())<jupyter_output>Brazil
China
United States
Russia<jupyter_text>__6-6. Polling:__ Use the code in favorite_languages.py (page 97).  • 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.<jupyter_code>favorite_languages ={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

people_list=["andreia","alex","sarah","edward","phil"]

for people in people_list:
    if people in favorite_languages.keys():
        print(f"{people.title()} thank you for taking our poll.")
        
    else:
        print(f"{people.title()} come and take to our poll.")<jupyter_output>Andreia come and take to our poll.
Alex come and take to our poll.
Sarah thank you for taking our poll.
Edward thank you for taking our poll.
Phil thank you for taking our poll.<jupyter_text>Nestingpage 105<jupyter_code>alien_0={'color':'green','points':5}
alien_1={'color':'yellow','points':10}
alien_2={'color':'red','points':15}

alien=[alien_0, alien_1, alien_2]

for alien in alien:
    print(alien)
    
#make an empty list to storing aliens.

aliens=[]

#make 30 green aliens

for alien_number in range(30):
    new_alien={'color':'green','points':5, 'speed':'slow'}
    aliens.append(new_alien)
    
#the the first 5 aliens

for alien in aliens[:5]:
    print(alien)
print("...")

#show how many alien have been created

print(f"Total number of aliens:{len(aliens)}.")
#make an empty list to storing aliens.

aliens=[]

#make 30 green aliens

for alien_number in range(30):
    new_alien={'color':'green','points':5, 'speed':'slow'}
    aliens.append(new_alien)
    
for alien in aliens[:3]:
    if alien['color']=="green":
        alien['color']="yellow"
        alien['points']=10
        alien['speed']='medium'
    

    
    
#the the first 5 aliens

for alien in aliens[:5]:
    print(alien)
print("...")

#show how many alien have been created

print(f"Total number of aliens:{len(aliens)}.")
#make an empty list to storing aliens.

aliens=[]

#make 30 green aliens

for alien_number in range(30):
    new_alien={'color':'green','points':5, 'speed':'slow'}
    aliens.append(new_alien)
    
for alien in aliens[:3]:
    if alien['color']=="green":
        alien['color']="yellow"
        alien['points']=10
        alien['speed']='medium'
    elif alien['color']=='yellow':
        alien['color']='red'
        alien['spped']='fast'
        alien['points']=15
        
    

    
    
#the the first 5 aliens

for alien in aliens[:5]:
    print(alien)
print("...")

#show how many alien have been created

print(f"Total number of aliens:{len(aliens)}.")<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'}
...
Total number of aliens:30.<jupyter_text>we stooped at the page 108  A list in a dictionary<jupyter_code>#Store information about a pizza being ordered.

pizza = {
    'crust':'thick',
    'toppings':['mushrroms','extra cheese'],
}

#summarize the order.

print(f"If you ordered a {pizza['crust']}-crust pizza "
      "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)
favorite_languages ={
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
}

for name, languages in favorite_languages.items():
    print(f"\n{name.title()}'s favorite languages are:")
    for language in languages:
        print(f"\t{language.title()}")

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

for name, languages in favorite_languages.items():
    if len(languages)>1:
        print(f"\n{name.title()}'s favorite languages are:")
        for language in languages:
            print(f"\t{language.title()}")
    else:
        print(f"\n{name.title()}'s'favorite language is:")
        for language in languages:
            print(f"\t{language.title()}")<jupyter_output>Jen's favorite languages are:
	Python
	Ruby

Sarah's'favorite language is:
	C

Edward's favorite languages are:
	Ruby
	Go

Phil's favorite languages are:
	Python
	Haskell<jupyter_text>A Dictionary in a dictionary<jupyter_code>users ={
    'aeinsten':{'first':'albert',
                "last":'aeinsten',
                'location':"princeton",
               },
    'mcurie':{
        'first':"marie",
        'last':'curie',
        'location':'paris',
    },
}

for username, user_info in users.items():
    print(f"\nUsername: {username}")
    full_name = f"{user_info['first']} {user_info['last']}"
    location = user_info['location']
    
    print(f"\tFull name: {full_name.title()}")
    print(f"\tLocation: {location.title()}")<jupyter_output>Username: aeinsten
	Full name: <NAME>
	Location: Princeton

Username: mcurie
	Full name: <NAME>
	Location: Paris<jupyter_text>Try it yourself at page 112 __6-7. People:__ Start with the program you wrote for Exercise 6-1 (page 99).  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.<jupyter_code>friend1_information ={"first_name":"Guilherme","last_name":"Thomazelli","age":39,"city":"sao paulo"}
friend2_information ={'first_name':"<NAME>","last_name":"Thomazelli",'age':6,'city':"sao paulo"}
friend3_information ={'first_name':"Renata","last_name":"Thomazelli","age":38,'city':"sao Paulo"}

Thomazelli_familly =[friend1_information,friend2_information, friend3_information]

for friend in Thomazelli_familly:
    print(f"\nIn this familly we have :\n"
          f"{friend['first_name']} {friend['last_name']} at the age {friend['age']}"
         f" living in the city of {friend['city']}.")
    
    print(f"{friend['first_name']}")<jupyter_output>In this familly we have :
<NAME> at the age 39 living in the city of sao paulo.
Guilherme

In this familly we have :
<NAME> at the age 6 living in the city of sao paulo.
<NAME>

In this familly we have :
<NAME> at the age 38 living in the city of sao Paulo.
Renata<jupyter_text>__6-8. Pets:__ Make several dictionaries, where each dictionary represents a differ-  ent 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.<jupyter_code>pet1={'kind':'dog', 'name':'rex','owner':'tiago'}
pet2={'kind':'cat','name':'melani','owner':'ana paula'}
pet3={'kind':'tartle','name':'flash','owner':'renata'}

pets =[pet1, pet2,pet3]


for pet in pets:
    print(f" {pet['owner'].title()} has a pet, it is a {pet['kind']} its name is {pet['name'].title()}")<jupyter_output>Tiago has a pet, it is a dog its name is Rex
 Ana Paula has a pet, it is a cat its name is Melani
 Renata has a pet, it is a tartle its name is Flash<jupyter_text>__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 places.<jupyter_code>favorite_places ={'andrea':'são Paulo','tiago':'damasceno','renata':'canadá'}

for name,favorite_place in favorite_places.items():
    print(f"{name.title()} favorite place is{favorite_place.title()}.")<jupyter_output>Andrea favorite place isSão Paulo.
Tiago favorite place isDamasceno.
Renata favorite place isCanadá.<jupyter_text>__6-10. Favorite Numbers:__ Modify your program from Exercise 6-2 (page 99)so each person can have more than one favorite number. Then print each per-  son’s name along with their favorite numbers.<jupyter_code>friends_numbers={'sara':[1,3,5],"john":[2,4,8],"israel":[3,6,9]}

for name,numbers in friends_numbers.items():
    
    print(f"\nMy friend {name.title()} likes these numbers:")
    for number in numbers:
        print(number)<jupyter_output>My friend Sara likes these numbers:
1
3
5

My friend John likes these numbers:
2
4
8

My friend Israel likes these numbers:
3
6
9<jupyter_text>__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 infor-  mation you have stored about it.<jupyter_code>cities ={'sao paulo':{'country':'brazil','population':"12.330.000"} ,'london':{'country':'England','population':"8.982.000"},\
         'vancouver':{'country':'canadá','population':"675.218"} }

for city,information in cities.items():
    print(f"\n{city.title()} is in {information['country'].title()}.")
    print(f"The city's population is {information['population']}.")
    if information['population']>"7.000.000":
        print("It's a large population.")<jupyter_output>Sao Paulo is in Brazil.
The city's population is 12.330.000.

London is in England.
The city's population is 8.982.000.
It's a large population.

Vancouver is in Canadá.
The city's population is 675.218.
{'fraction_non_alphanumeric': 0.13350985284383116, 'fraction_numerical': 0.012933448749936351, 'mean_word_length': 4.710962489095667, 'pattern_counts': {'":': 28, '<': 69, '<?xml version=': 0, '>': 96, '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': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '455886', 'license': 'MIT', 'n_tokens_mistral': 6648, 'n_tokens_neox': 6290, 'n_words': 2105, 'path': 'Ex6_Working_with_dictionaries_and_loops.ipynb', 'repo_name': 'Renata-Thomazelli/ProjectsinPython', 'size': '19698'}