深度阅读

How to loop through all key-value pairs in a dictionary?

作者
作者
2023年08月22日
更新时间
6.9 分钟
阅读时间
0
阅读量

To loop through all key-value pairs in a Python dictionary, you can use the items() method. Here is an example of how to iterate over all the key-value pairs in a dictionary using the items() method:

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
for key, value in my_dict.items():
    print(key, value)

This will output:

key1 value1
key2 value2
key3 value3

In this example, items() returns a list of tuples, where each tuple contains a key-value pair from the dictionary. The for loop iterates over the tuples and unpacks each tuple into two variables, key and value, which you can use to access the key and value for each iteration.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。