程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

0 basic learning python (18)

編輯:Python

Ergodic dictionary

stay python A dictionary may contain several key value pairs or hundreds of key value pairs ,python Indicates that the key value pairs in the dictionary will be traversed , Dictionaries can be used to store all kinds of information , So we can traverse all key value pairs in the dictionary , You can also just iterate over keys or values .
First, let's look at a dictionary that stores information about Internet users , Now save the user name and name in the dictionary .

user_0={

'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key,value in user_0.items():
print(f"\nKey:{
key}")
print(f"Value:{
value}")
Key:username
Value:efermi
Key:first
Value:enrico
Key:last
Value:fermi

To write a traversal dictionary for loop , You can declare two variables , Used to store keys and values in key value pairs , These two variables can be any name .for The second part of the statement contains the dictionary name and method items(), It returns a list of key value pairs . Next for The loop assigns the amount of each key value pair to two specified variables in turn . Use these two variables to print each key and each value , And use \n Make sure to insert a blank line before each key value pair .

Traversal keys

When we don't need dictionary values keys() It is useful to .

user_0={

'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key in user_0.keys():
print(key.title())
Username
First
Last

We use keys() Extract all the key values , And then assign it to the variable name, Let him print out .
Of course, we can also use in the process of traversal sorted() Sort .

user_0={

'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for name in sorted(user_0.keys()):
print(f"{
name.title()},thank you .")
First,thank oyu.
Last,thank you.
Username,thank you

This makes the keys an alphabetical sort . And then output .

Traversal value

Traversal values and keys are the same for Statement to extract each value from the dictionary and assign the value to the variable in turn .

user_0={

'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for value in user_0.values():
print(user_0.title())
Efermi
Enrico
Fermi

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved