python 遍历字典

在Python中,遍历字典(dictionary)通常涉及遍历字典的键(keys)、值(values)或者同时遍历键和值。以下是几种常见的遍历字典的方法:

  1. 遍历字典的键(keys):
pythonmy_dict = {
'a': 1,
'b': 2,
'c': 3
}

for key in my_dict.keys():
print(key)
  1. 遍历字典的值(values):
pythonfor value in my_dict.values():
print(value)
  1. 同时遍历字典的键和值:
pythonfor key, value in my_dict.items():
print(key, value)
  1. 使用dict.items()方法遍历字典的键值对,并将其解包到变量中:
pythonfor k, v in my_dict.items():
print(k, v)
  1. 如果你想要遍历字典的键、值以及字典本身,你可以使用enumerate()函数:
pythonfor index, (key, value) in enumerate(my_dict.items()):
print(f"Index: {index}, Key: {key}, Value: {value}")

这里是一个完整的例子,展示了如何遍历字典的键、值和键值对:

pythonmy_dict = {
'apple': 1,
'banana': 2,
'cherry': 3
}

# 遍历键
print("Keys:")
for key in my_dict.keys():
print(key)

# 遍历值
print("Values:")
for value in my_dict.values():
print(value)

# 同时遍历键和值
print("Key-Value Pairs:")
for key, value in my_dict.items():
print(key, value)

# 使用enumerate遍历键、值和字典本身
print("With enumerate:")
for index, (key, value) in enumerate(my_dict.items()):
print(f"Index: {index}, Key: {key}, Value: {value}")

运行这段代码将会输出:

Keys:
apple
banana
cherry
Values:
1
2
3
Key-Value Pairs:
apple 1
banana 2
cherry 3
With enumerate:
Index: 0, Key: apple, Value: 1
Index: 1, Key: banana, Value: 2
Index: 2, Key: cherry, Value: 3
posted @ 2024-04-03 19:41  奥兰王子  阅读(47)  评论(0编辑  收藏  举报