In Python, you can create a dictionary using a list by using the zip()
function to combine two lists into a sequence of key-value pairs, and then passing that sequence to the dict()
constructor. Here’s an example:
keys = ['key1', 'key2', 'key3']
values = ['value1', 'value2', 'value3']
my_dict = dict(zip(keys, values))
print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
In this example, we create two lists keys
and values
containing the desired keys and values for the dictionary. We then use the zip()
function to combine the two lists into a sequence of key-value pairs, and pass that sequence to the dict()
constructor to create the dictionary.
Note that if the two lists are of unequal length, the resulting dictionary will only include the key-value pairs for the first n
elements, where n
is the length of the shorter list. If the two lists are of different types, you may need to convert one or both of them to a compatible type before using zip()
.
+ There are no comments
Add yours