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

Several traversal methods of Python Dictionary (dict)

編輯:Python

1. Use for key in dict Ergodic dictionary
have access to for key in dict Traverse all the keys in the dictionary
x = {'a': 'A', 'b': 'B'} for key in x: print(key) # Output results a b
2. Use for key in dict.keys () Traverse the key of the dictionary
The dictionary provides keys () Method returns all keys in the dictionary
# keys book = { 'title': 'Python', 'author': '-----', 'press': ' Life is too short , I use python' } for key in book.keys(): print(key) # Output results title author press
3. Use for item in dict.items () Traverse the key value pairs of the dictionary
The dictionary provides items () Method returns all key value pairs in the dictionary item
Key value pair item It's a tuple ( The first 0 Item is a key 、 The first 1 Items are values )
x = {'a': 'A', 'b': 'B'} for item in x.items(): key = item[0] value = item[1] print('%s %s:%s' % (item, key, value)) # Output results ('a', 'A') a:A ('b', 'B') b:B
4. Use for key,value in dict.items () Traverse the key value pairs of the dictionary
Tuples are in = On the right side of the assignment operator , The brackets can be omitted
item = (1, 2) a, b = item print(a, b) # Output results 1 2
example :
x = {'a': 'A', 'b': 'B'} for key, value in x.items(): print('%s:%s' % (key, value)) # Output results a:A b:B        5. Use for values in dict.values () Traversal dictionary value
The dictionary provides values () Method returns all the values in the dictionary
values book = { 'title': 'Python', 'author': '-----', 'press': ' Life is too short , Cherish the people around you ' } for value in book.values(): print(value) # Output results Python ----- Life is too short , Cherish the people around you


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