深度阅读

How to create a dictionary from two lists in Python?

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

To create a dictionary from two lists in Python, you can use a dictionary comprehension or the zip() function. Here are some examples:

Using a dictionary comprehension:

keys = ['key1', 'key2', 'key3']
values = [10, 45, 23]
my_dict = {keys[i]: values[i] for i in range(len(keys))}
print(my_dict)  # Output: {'key1': 10, 'key2': 45, 'key3': 23}

In this example, a dictionary comprehension is used to create a dictionary where the keys are taken from the keys list and the values from the values list. To iterate over both lists at the same time, range(len(keys)) is used to generate a sequence of indices that is passed to the dictionary comprehension.

Using the zip() function:

keys = ['key1', 'key2', 'key3']
values = [10, 45, 23]
my_dict = dict(zip(keys, values))
print(my_dict)  # Output: {'key1': 10, 'key2': 45, 'key3': 23}

In this example, the zip() function is used to create pairs of keys and values from the keys and values lists, and then the dict() constructor is called to create a dictionary from the pairs.

Note that both methods assume that the lists have the same length and that the order of the elements in both lists are correlated (i.e., the first element in the keys list corresponds to the first element in the values list, and so on). If you have duplicate keys or values, the second occurrence will overwrite the first one in the resulting dictionary. Also, if the lists have different lengths, you will get a ValueError from the zip() function.

相关标签

博客作者

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