![]() |
VOOZH | about |
We are given two lists, we need to convert both of the list into dictionary. For example we are given two lists a = ["name", "age", "city"], b = ["Geeks", 30,"Delhi"], we need to convert these two list into a form of dictionary so that the output should be like {'name': 'Geeks', 'age': 30, 'city': 'Delhi'}. We can do this using methods like zip, dictionary comprehension , itertools.starmap. Let's implement these methods practically.
Use zip to pair elements from two lists, where the first list provides the keys and second provides the values after that we convert the zipped object into a dictionary using dict() which creates key-value pairs.
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
Use dictionary comprehension to iterate over the pairs generated by zip(a, b), creating key-value pairs where elements from list a are the keys and elements from list b are the values. This creates the dictionary in a single concise expression.
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
Iterate through both lists simultaneously using zip and for each pair, add the first element as the key and second as the value to the dictionary.
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
Use itertools.starmap to apply a lambda function that takes two arguments (key and value) to each pair generated by zip(a, b). This creates key-value pairs and passes them directly into dict() to form dictionary.
{'name': 'Alice', 'age': 30, 'city': 'New York'}
Explanation:
Related Articles: