The 6th chapter mainly exercises the various dictionaries, the following content
What is a dictionary
Relationship of key-value in dictionary
A simple dictionary.
Find its corresponding value by using the keys in the dictionary
Add a key-value to the dictionary
To modify a value in a dictionary
Traversing key values in a dictionary to items ()
Iterate through the keys in the Dictionary keys ()
Iterate through the values in the dictionary value ()
Iterate through the values in the dictionary and go to Duplicate set ()
Nested dictionaries in lists
Add a dictionary to the same list with a For loop
Store a list in a dictionary and print
What is a dictionary?
I'm going to make an immature summary: It's a high-level list, why is it a high-level list, because the elements in the list are single, no attributes
The dictionary can specify properties. For example: Your name is Zhang San, you can only store Zhang San name in the list, and the dictionary can be stored as---name: Zhang San
The dictionary uses curly braces {}
List using brackets []
Tuples using parentheses ()
Key-value relationships in a dictionary
For example, this simple list alien_0 = {' Color ': ' green ', ' Points ': 5}
Color is the key, green is the value
A simple dictionary.
Get the relevant value by key
------------------------------------------------
Alien_0 = {' Color ': ' green ', ' Points ': 5}
Print (alien_0[' color ')
Print (alien_0[' points ')
------------------------------------------------
Green
5
How to reference a value in a dictionary
A variable is defined by the value obtained from the key in the dictionary and referenced in print
------------------------------------------------------------------------
Alien_0 = {' Color ': ' green ', ' Points ': 5}
new_points = alien_0[' points ']
Print ("You just earned" + str (new_points) + "points!")
------------------------------------------------------------------------
You just earned 5 points!
add key-value
In the Alien_0 dictionary, add two key-value pairs
----------------------------------------------------------------------------
Alien_0 = {' Color ': ' green ', ' Points ': 5}
Print (ALIEN_0)
alien_0[' x_position '] = 0
alien_0[' y_position '] =
Print (ALIEN_0)
-----------------------------------------------------------------------------
{' Color ': ' green ', ' Points ': 5}
{' Color ': ' green ', ' points ': 5, ' x_position ': 0, ' y_position ': 25}
Add a key-value pair to an empty dictionary
----------------------------------
Alien_0 = {}
alien_0[' color ' = ' green '
alien_0[' points '] = 5
Print (ALIEN_0)
-----------------------------------
{' Color ': ' green ', ' Points ': 5}
To modify a value in a dictionary
---------------------------------------------------------------
Alien_0 = {' Color ': ' Green '}
Print ("The Alien is" + alien_0[' color ') + ".")
alien_0[' color ' = ' yellow '
Print ("The Alien is now" + alien_0[' color ') + ".")
---------------------------------------------------------------
The alien is green.
The alien is now yellow.
Delete a key value pair
Same as list, use Del to delete key values from the dictionary (delete permanently)
------------------------------------------------
Alien_0 = {' Color ': ' green ', ' Points ': 5}
Print (ALIEN_0)
del alien_0[' points ']
Print (ALIEN_0)
-------------------------------------------------
{' Color ': ' green ', ' Points ': 5}
{' Color ': ' Green '}
A dictionary consisting of similar objects
Calling values in a dictionary by key
-------------------------------------------------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
Print ("Sarah ' s favorite language is" + favorite_languages[' Sarah '].title () + ".")
-------------------------------------------------------------------------------------------
Sarah ' s favorite language is C.
Items () Traverse all key-value pairs
This dictionary can be traversed through a simple for loop
-----------------------------------------
User_0 = {
' username ': ' Efermi ',
' First ': ' Enrico ',
' Last ': ' Fermi ',
}
For key, value in User_0.items ():
Print ("\nkey:" + key)
Print ("Value:" + value)
------------------------------------------
Key:username
Value:efermi
Key:first
Value:enrico
Key:last
Value:fermi
A small instance of traversing a dictionary
-------------------------------------------------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
For name, language in Favorite_languages.items ():
Print (Name.title () + "s favorite language is" + language.title () + ".")
-------------------------------------------------------------------------------------------
Jen ' s favorite language is Python.
Sarah ' s favorite language is C.
Edward ' s favorite language is Ruby.
Phil ' s favorite language is Python.
Keys () Iterate through all the keys of the dictionary
It doesn't matter if you don't add keys (), because the dictionary iterates through all the keys by default.
It's more clear.
--------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
For name in Favorite_languages.keys ():
Print (Name.title ())
---------------------------------------------------
Jen
Sarah
Edward
Phil
To iterate through the contents of a dictionary using a for loop
and define a list to do if judgment if the for loop has a list of elements
Just print a word.
-------------------------------------------------------------------------------------------
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 () + "!")
-------------------------------------------------------------------------------------------
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is python!
Use the keys () traversal to check if the keys in the dictionary have the specified characters, and make the If judgment
If the Erin does not exist in the dictionary, specify print
-----------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
If ' Erin ' not in Favorite_languages.keys ():
Print ("Erin, poll!")
------------------------------------------------------
Erin, poll!
Iterate through all the keys in a dictionary sequentially
Call sorted () to sort
-------------------------------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
For name in sorted (Favorite_languages.keys ()):
Print (Name.title () + ", thank you for taking the poll.")
-------------------------------------------------------------------------
Edward, thank you for taking the poll.
Jen, thank for taking the poll.
Phil, thank for taking the poll.
Sarah, thank you for taking the poll.
Value () iterates through all the values in the dictionary and capitalizes
---------------------------------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
Print ("The following languages has been mentioned:")
For language in Favorite_languages.values ():
Print (Language.title ())
---------------------------------------------------------------------------
The following languages has been mentioned:
Python
C
Ruby
Python
You can use Set () to remove duplicates in case of more data
Set () Collection
--------------------------------------------------------------------------
Favorite_languages = {
' Jen ': ' Python ',
' Sarah ': ' C ',
' Edward ': ' Ruby ',
' Phil ': ' Python ',
}
Print ("The following languages has been mentioned:")
For language in set(Favorite_languages.values ()):
Print (Language.title ())
--------------------------------------------------------------------------
The following languages has been mentioned:
Python
C
Ruby
Nesting: Nested dictionaries in lists
----------------------------------------------------
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)
----------------------------------------------------
{' Color ': ' green ', ' Points ': 5}
{' Color ': ' Yellow ', ' Points ': 10}
{' Color ': ' Red ', ' points ': 15}
Create a dictionary list using loops
For Loop 30 times, place the New_alien dictionary in the Aliens list
5 times before printing
Calculate the length of the Aliens list with Len ()
---------------------------------------------------------------------------
Aliens = []
For Alien_number in range (30):
New_alien = {' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
Aliens.append (New_alien)
For alien in Aliens[:5]:
Print (alien)
Print ("...")
Print ("Total number of Aliens:" + str (len (aliens)))
---------------------------------------------------------------------------
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
...
Total number of aliens:30
Compare and change values in a dictionary loop
Define an empty list aliens, loop the list of New_alien 30 times to the Aliens list
The second for loop first determines the aliens slice.
= = is the comparison
= Change is made
The third for loop is the first 5 elements of the print aliens list, and you can see that the changes are different
----------------------------------------------------------------------------
Aliens = []
For Alien_number in range (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)
Print ("...")
----------------------------------------------------------------------------
{' Color ': ' Yellow ', ' points ': ten, ' Speed ': ' Medium '}
{' Color ': ' Yellow ', ' points ': ten, ' Speed ': ' Medium '}
{' Color ': ' Yellow ', ' points ': ten, ' Speed ': ' Medium '}
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
{' Color ': ' green ', ' points ': 5, ' speed ': ' Slow '}
...
Store a list in a dictionary
There are two values in the toppings list in the Pizza dictionary, which can be printed separately
--------------------------------------------------------------------------------------------------------------- ---
Pizza = {
' Crust ': ' thick ',
' Toppings ': [' mushrooms ', ' extra cheese ']
}
Print ("You ordered a" + pizza[' crust ') + "-crust Pizza" + "with the following toppings:")
For topping in pizza[' toppings ']:
print ("\ t" + topping)
--------------------------------------------------------------------------------------------------------------- ---
You ordered a thick-crust pizza with the following toppings:
Mushrooms
Extra cheese
A For loop on the dictionary, looping the elements of the list in the dictionary again
-------------------------------------------------------------------------------
Favorite_languages = {
' Jen ': [' python ', ' Ruby '],
' Sarah ': [' C '],
' Edward ': [' Ruby ', ' Go '],
' Phil ': [' python ', ' Haskell '],
}
For name, languages in Favorite_languages.items ():
Print ("\ n" + name.title () + "' s favorite languages is:")
For language in languages:
Print ("\ T" + language.title ())
-------------------------------------------------------------------------------
Jen ' s favorite languages is:
Python
Ruby
Sarah ' s favorite languages is:
C
Edward ' s favorite languages is:
Ruby
Go
Phil ' s favorite languages is:
Python
Haskell
This article is from the "LULU" blog, make sure to keep this source http://aby028.blog.51cto.com/5371905/1965190
Getting started with Python programming to Practice-notes (Chapter 6)