1, the basic situation of the dictionary is key:value, such a key-value pair mode, and the dictionary can store the amount of information is almost unrestricted. The corresponding value is obtained by accessing the key. Use between keys and values (:) separate. The dictionary is denoted by {}, and the elements in the dictionary are separated by (,). The simplest dictionary is as follows:
Alien_0 = {' Color ': ' green ', ' point ': 5}
Here ' color ' and ' point ' are a key, ' green ' and 5 are a value.
2, in order to get the value of a key in the dictionary, you can directly access the keys in the dictionary:
>>> alien_0 = {' Color ': ' Green '}
>>> print (alien_0[' color ')
Green
3. Add key-value pairs:
>>> Print (ALIEN_0)
{' Color ': ' Green '}
>>> alien_0[' x '] = 0
>>> alien_0[' y '] = 100
>>> Print (ALIEN_0)
{' X ': 0, ' y ': +, ' color ': ' Green '}
Note that dictionaries do not care about the order of arrangement, that is, the addition of order and order is not related. The dictionary only cares about the relationship between the key and the value.
4, using a dictionary to store user-supplied data or when writing code that can automatically generate a large number of key-value pairs, it is usually necessary to define an empty dictionary first:
>>> alien_0 = {}
>>> alien_0[' color ' = ' green '
>>> alien_0[' points '] = 5
>>> Print (ALIEN_0)
{' Points ': 5, ' color ': ' Green '}
5. Modify the values in the dictionary:
>>> Print (ALIEN_0)
{' Points ': 5, ' color ': ' Green '}
>>> alien_0[' points '] = 6
>>> Print (ALIEN_0)
{' Points ': 6, ' color ': ' Green '}
is to change the key in the dictionary to the new value, which is to modify the values in the keys in the dictionaries.
6. Delete the key value pairs:
>>> Print (ALIEN_0)
{' Points ': 6, ' color ': ' Green '}
>>> del alien_0[' points ']
>>> Print (ALIEN_0)
{' Color ': ' Green '}
Note that when deleted, the minus-value pair is deleted together. is to disappear forever, not temporarily.
7, for a longer dictionary, you can use the Python indentation with line wrapping to achieve an elegant type of dictionary key-value pairs:
>>> languages = {
... ' Alex ': ' Python ',
... ' Ruifeng ': ' C ',
... ' Johnny ': ' Perl ',
... }
>>> Print (languages)
{' Ruifeng ': ' C ', ' Johnny ': ' Perl ', ' Alex ': ' Python '}
As you can see, the key-value pairs in the dictionary are indented and added (,) after the last key-value pair. For other things that need to be entered very long, such as the text in the print () function that needs to be entered is very long, you can continue to write in (), and the new line needs to be indented.
8. The special extraction of the ergodic key-value pairs:
>>> Print (my_friend_1)
{' Sex ': ' Male ', ' age ': ' + ', ' City ': ' Shanghai ', ' name ': ' Cao Xiao June '}
>>> for key, value in My_friend_1.items ():
... print ("\nkey:" + key)
... print ("Value:" + value)
...
Key:sex
Value:male
Key:age
Value:31
Key:city
Value:shanghai
Key:name
Value:cao Xiao June
The items () method is used to return a list of key-value pairs. After that, the keys are stored in the key variable, and the value is saved to the value variable. "\ n" means inserting a carriage return symbol. Note that even traversing a dictionary is not a concern in order, because the core of the dictionary is the correlation of key-value pairs.
9, the above is a key-value pair, if you only need to take the key, and do not need a value, then use the keys () method:
>>> Print (my_friend_1)
{' Sex ': ' Male ', ' age ': ' + ', ' City ': ' Shanghai ', ' name ': ' Cao Xiao June '}
>>> for key in My_friend_1.keys ():
... print ("\nkey:" + key)
...
Key:sex
Key:age
Key:city
Key:name
If the keys () method is omitted, that is, for key in My_friend_1:, the default is the key, but it is recommended to write so that it is easy to read.
10, the dictionary traversal is not sorted, if you really need to sort the output, you can manually intervene, using the sorted () function:
>>> for thing in Sorted (My_friend_1.keys ()):
.. print (Thing)
...
Age
City
Name
Sex
11. If you need to traverse a value in a dictionary, you can use the values () method, which returns a list of values but does not contain keys:
>>> Print (my_friend_1)
{' Sex ': ' Male ', ' age ': ' + ', ' City ': ' Shanghai ', ' name ': ' Cao Xiao June '}
>>> for values in My_friend_1.values ():
.. print (values)
...
Male
31
Shanghai
Cao Xiao June
Given that values are sometimes duplicated, using the set () function, you can remove duplicates:
>>> Print (my_friend_1)
{' Sex ': ' Male ', ' new ': ' ' name ': ' Cao Xiao June ', ' City ': ' Shanghai ', ' new_1 ': ' + ', ' age ': ' 31 '}
>>> for I in Set (My_friend_1.values ()):
... print (i)
...
Cao Xiao June
Male
Shanghai
31
31
12. Store a series of dictionaries in a list, or store the list as a value in a dictionary, which is called nesting. You can nest dictionaries in lists, nest lists in dictionaries, and even nest dictionaries in dictionaries.
#!/usr/bin/env Python3
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)
This is a typical nesting, the dictionary as a value, written to the list, this time traversing the list, is the print list of each element, that is, each dictionary:
[Email protected] ex-python]#./name_cases.py
{' Color ': ' green ', ' Points ': 5}
{' Color ': ' Yellow ', ' Points ': 10}
{' Color ': ' Red ', ' points ': 15}
An example of a nested loop:
#!/usr/bin/env Python3
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)))
Where for Alien_number in range (30):, that is, to represent the loop 30 times.
This is a special way of writing, you can see alien_number this variable in the next statement does not appear, with range (30) [that is, the range (0,30)] function, to achieve the loop 30 times the effect.
13. Store the list in the dictionary:
[email protected] ex-python]# cat name_cases.py
#!/usr/bin/env Python3
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 ())
Output:
[Email protected] ex-python]#./name_cases.py
Phil ' s favorite languages is:
Python
Haskell
Jen ' s favorite languages is:
Python
Ruby
Edward ' s favorite languages is:
Ruby
Go
Sarah ' s favorite languages is:
C
14. Store the dictionary in a dictionary, but this code is likely to be complicated quickly:
[email protected] ex-python]# cat name_cases.py
#!/usr/bin/env Python3
Users = {
' user_1 ': {
' First ': ' Alex ',
' Last ': ' Hou ',
' Location ': ' Dalian ',
},
' user_2 ': {
' First ': ' Johnny ',
' Last ': ' Zhu ',
' Location ': ' Shanghai ',
},
}
For username, user_info in Users.items ():
Print ("\nusername:" + username)
Full_name = user_info[' first ' + "" + user_info[' last ']
Location = user_info[' Location ']
Print ("\tfull name:" + full_name.title ())
Print ("\tlocation:" + location.title ())
Output:
[Email protected] ex-python]#./name_cases.py
Username:user_1
Full Name:alex Hou
Location:dalian
Username:user_2
Full Name:johnny Zhu
Location:shanghai
This article is from the "Alex Blog" blog, make sure to keep this source http://houjun19830610.blog.51cto.com/9269760/1847229
"Python Beginner-6" dictionary