You can convert a list to a dictionary in Python using the dict()
function. The basic syntax of dict()
function is:
dict(list)
Where list
is the list that you want to convert to a dictionary.
The list should contain key-value pairs as a tuple or a list, where the first element is the key and the second element is the value. Here’s an example:
my_list = [('a', 1), ('b', 2), ('c', 3)] my_dict = dict(my_list) print(my_dict)
Output:
{'a': 1, 'b': 2, 'c': 3}
You can also use a list comprehension to create a list of dictionaries. Here’s an example:
my_list = ['apple', 'banana', 'orange'] my_dict = {fruit: len(fruit) for fruit in my_list} print(my_dict)
Output:
{'apple': 5, 'banana': 6, 'orange': 6}
In this example, the keys are the fruits, and the values are the length of the fruits.
Using zip() function:
Yes, you can also use the zip()
function to convert two lists into a dictionary. The zip()
function returns an iterator that combines elements from multiple iterable objects into tuples.
Here’s an example:
keys = ['a', 'b', 'c'] values = [1, 2, 3] my_dict = dict(zip(keys, values)) print(my_dict)
Output:
{'a': 1, 'b': 2, 'c': 3}
In this example, the zip()
function combines the elements from keys
and values
into tuples, and then the dict()
function converts the tuples into key-value pairs in a dictionary. The first element of each tuple becomes a key, and the second element becomes a value.