Several traversal methods of Python dictionary dict

  • 2021-12-12 05:05:19
  • OfStack

Directory 1. Use for key in dict to traverse the dictionary 2. Use for key in dict. keys () to traverse the dictionary's keys 3. Use for values in dict. values () to traverse the dictionary's values 4. Use for item in dict () to traverse the dictionary's key-value pairs 5. Use for key, value in dict. items () to traverse the dictionary's key-value pairs

1. Use for key in dict to traverse the dictionary

You can use the for key in dict Traverse all the keys in the dictionary


x = {'a': 'A', 'b': 'B'}
for key in x:
    print(key)


#  Output result 
a
b

2. Use for key in dict. keys () to traverse the dictionary's keys

The dictionary provides keys () Method returns all the 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 result 
title
author
press

3. Use for values in dict. values () to traverse the dictionary values

The dictionary provides values () Method returns all the values in the dictionary


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 725638078
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
# values
book = {
    'title': 'Python',
    'author': '-----',
    'press': ' Life is too short, I use python'
}

for value in book.values():
    print(value)


#  Output result 
Python
-----
 Life is too short, I use python

4. Use for item in dict. items () to traverse the dictionary's key-value pairs

The dictionary provides items () Method returns all key-value pairs in the dictionary item
Key-value pair item Is 1 tuple (item 0 is the key and item 1 is the value)


x = {'a': 'A', 'b': 'B'}
for item in x.items():
    key = item[0]
    value = item[1]
    print('%s   %s:%s' % (item, key, value))


#  Output result 
('a', 'A')   a:A
('b', 'B')   b:B

5. Use for key, value in dict. items () to traverse the key-value pairs in the dictionary

You can omit parentheses when tuples are to the right of the = assignment operator


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 725638078
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
item = (1, 2)
a, b = item
print(a, b)


#  Output result 
1 2


Example:


x = {'a': 'A', 'b': 'B'}
for key, value in x.items():
    print('%s:%s' % (key, value))


#  Output result 
a:A
b:B

Related articles: