📜  在Python中遍历字典

📅  最后修改于: 2022-05-13 01:55:35.932000             🧑  作者: Mango

在Python中遍历字典

Python中的字典是数据值的无序集合,用于像地图一样存储数据值,与其他仅将单个值作为元素保存的数据类型不同,字典保存key:value对。

在Python中有多种方法可以遍历字典。

  • 遍历所有键
  • 遍历所有值
  • 遍历所有键值对

遍历所有键:

下面代码中的状态顺序每次都会改变,因为字典没有按特定顺序存储键。

# Python3 code to iterate through all keys in a dictionary
  
statesAndCapitals = {
                     'Gujarat' : 'Gandhinagar',
                     'Maharashtra' : 'Mumbai',
                     'Rajasthan' : 'Jaipur',
                     'Bihar' : 'Patna'
                    }
                      
print('List Of given states:\n')
  
# Iterating over keys
for state in statesAndCapitals:
    print(state)
输出:
List Of given states:

Rajasthan
Bihar
Maharashtra
Gujarat

为了维护字典中键和值的顺序,请使用 OrderedDict。

# Python3 code to iterate through all keys 
# in a dictionary in a specific order
  
from collections import OrderedDict
  
statesAndCapitals = OrderedDict([
                                 ('Gujarat', 'Gandhinagar'),
                                 ('Maharashtra', 'Mumbai'),
                                 ('Rajasthan', 'Jaipur'),
                                 ('Bihar', 'Patna')
                                ])
                      
print('List Of given states:\n')
  
# Iterating over keys
for state in statesAndCapitals:
    print(state)
输出:
List Of given states:

Gujarat
Maharashtra
Rajasthan
Bihar

上面的字典是一个OrderedDict ,因为键和值是按照它们在字典中定义的顺序存储的。因此,当我们想要维护字典中存储的(键,值)的顺序时,应该使用上述方法。


遍历所有值:

同样,在这种情况下,在下面的代码中打印大写的顺序每次都会改变,因为字典不会以特定的顺序存储它们。

# Python3 code to iterate through all values in a dictionary
  
statesAndCapitals = {
                     'Gujarat' : 'Gandhinagar',
                     'Maharashtra' : 'Mumbai',
                     'Rajasthan' : 'Jaipur',
                     'Bihar' : 'Patna'
                    }
                      
print('List Of given capitals:\n')
  
# Iterating over values
for capital in statesAndCapitals.values():
    print(capital)
输出:
List Of given capitals:

Gandhinagar
Jaipur
Mumbai
Patna

遍历所有键值对:

# Python3 code to iterate through all key, value 
# pairs in a dictionary
  
statesAndCapitals = {
                     'Gujarat' : 'Gandhinagar',
                     'Maharashtra' : 'Mumbai',
                     'Rajasthan' : 'Jaipur',
                     'Bihar' : 'Patna'
                    }
                      
print('List Of given states and their capitals:\n')
  
# Iterating over values
for state, capital in statesAndCapitals.items():
    print(state, ":", capital)
输出:
List Of given states and their capitals:

Bihar : Patna
Gujarat : Gandhinagar
Rajasthan : Jaipur
Maharashtra : Mumbai