![]() |
VOOZH | about |
We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into list of dictionaries so that the output should be [{'name': 'Geeks', 'age': 25, 'city': 'New York'}, {'name': 'Geeks', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Geeks', 'age': 22, 'city': 'Chicago'}] . For this we can use multiple methods like zip, dictionary comprehension ,map.
zip() function pairs keys from a with values from each sublist in b and dict() converts these pairs into dictionaries, which are collected into a list using list comprehension.
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 22, 'city': 'Chicago'}]
Explanation:
Dictionary comprehension {key: value for key, value in zip(a, values)} creates a dictionary by pairing keys from a with values from a sublist in b using zip(). A list comprehension wraps this to generate a list of dictionaries for all sublists in b.
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 22, 'city': 'Chicago'}]
Explanation:
map() function applies a function to each sublist in a, where the function zips the keys from b with the values in the sublist and converts them into dictionaries. The result is then collected into a list using list().
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 22, 'city': 'Chicago'}]
Explanation:
A for loop iterates through each sublist in b and a dictionary comprehension creates a dictionary by pairing keys from a with corresponding values from the sublist. Each dictionary is appended to the result list res
[{'name': ['Alice', 25, 'New York'], 'age': ['Bob', 30, 'Los Angeles'], 'city': ['Charlie', 22, 'Chicago']}, {'name': ['Alice', 25, 'New York'], 'age': ['Bob', 30, 'Los Angeles'], 'city': ['Charlie', ...Explanation: