深度阅读

How to create a dictionary from two lists in python

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

To create a dictionary from two lists in Python, you can use the built-in zip() function with the dict() constructor. Here’s an example:

keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = dict(zip(keys, values))
print(my_dict)

In this example, the zip() function is used to pair up the elements of the keys and values lists, and then the dict() constructor is used to convert the resulting list of pairs into a dictionary. The output will be 'a': 1, 'b': 2, 'c': 3 .

If the two lists have different lengths, the resulting dictionary will have the length of the shorter list. You can also convert the lists into tuples or sets before using zip() to create a dictionary.

Note that if the lists have duplicate values, the resulting dictionary will have the last value in the list for each key. If you want to preserve all the values, you can use a dictionary comprehension with the zip() function:

keys = ['a', 'b', 'c', 'a']
values = [1, 2, 3, 4]
my_dict = { k:v for k,v in zip(keys, values) }
print(my_dict)

In this example, the duplicate key 'a' is present in the keys list, so the resulting dictionary will have the value 4 for that key. The output will be 'a': 4, 'b': 2, 'c': 3 .

相关标签

博客作者

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