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