深度阅读

How can to get list of values from dictionary in Python?

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

To get a list of values from a dictionary in Python

To get a list of values from a dictionary in Python, you can use the values() function. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
values_list = list(my_dict.values())

print(values_list)

Output:

[1, 2, 3]

In this example, we define a dictionary my_dict with key-value pairs. We then use the values() function to obtain a list of values from the dictionary, and convert it to a list using the list() function. Finally, we print the resulting list values_list.

To iterate over the keys and values in a dictionary in Python

To iterate over the keys and values in a dictionary in Python, you can use the items() method. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in my_dict.items():
    print(f"Key: {key}, Value: {value}")

Output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3

In this example, we define a dictionary my_dict with key-value pairs. We then use a for loop to iterate over each key-value pair in the dictionary, utilizing the items() method to return an iterable of the key-value pairs as tuples. The key, value notation used in the loop assigns the key and value to separate variables. Finally, we print out the keys and values for each iteration.

相关标签

博客作者

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