Python - Convert List to List of dictionaries
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.
Using zip()
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.
a = ["name", "age", "city"]
b = [["Alice", 25, "New York"], ["Bob", 30, "Los Angeles"], ["Charlie", 22, "Chicago"]]
# Create a list of dictionaries by zipping keys with each sublist of values
ans = [dict(zip(a, values)) for values in b]
print(ans)
Output
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 22, 'city': 'Chicago'}]
Explanation:
- zip(a, values) pairs keys from a with corresponding values from each sublist in b, creating key-value pairs.
- List comprehension converts each paired sublist into a dictionary using dict() and collects all dictionaries into a list.
Using a Dictionary Comprehension
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.
a = [["Alice", 25, "New York"], ["Bob", 30, "Los Angeles"], ["Charlie", 22, "Chicago"]] # List of values
b = ["name", "age", "city"] # List of keys
# Create dictionaries by pairing keys from 'b' with values from each sublist in 'a'
res = [{b[i]: value[i] for i in range(len(b))} for value in a]
print(res)
Output
[{'name': 'Alice', 'age': 25, 'city': 'New York'}, {'name': 'Bob', 'age': 30, 'city': 'Los Angeles'}, {'name': 'Charlie', 'age': 22, 'city': 'Chicago'}]
Explanation:
- List comprehension iterates over each sublist in a and creates a dictionary by pairing keys from b with corresponding values from the sublist using their index positions.
- Each generated dictionary is added to a list, resulting in a list of dictionaries where each dictionary represents a set of key-value pairs from a sublist in a.
Using map()
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().
a = ["name", "age", "city"] # Keys for dictionaries
b = [["Alice", 25, "New York"], ["Bob", 30, "Los Angeles"], ["Charlie", 22, "Chicago"]] # Values
# Use map with a lambda to zip keys and values, then convert to a list of dictionaries
res = list(map(lambda x: dict(zip(a, x)), b))
print(res)
Output
[{'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 lambda that zips each sublist in b (values) with the keys from a, creating key-value pairs.
- map() function produces an iterator, which is then converted to a list of dictionaries, where each dictionary represents a key-value mapping from the zipped values.
Using a Loop
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
a = ["name", "age", "city"] # List of keys
b = [["Alice", 25, "New York"], ["Bob", 30, "Los Angeles"], ["Charlie", 22, "Chicago"]] # List of values
# Iterate through each sublist in 'b' and create a dictionary by pairing keys from 'a' with values from the sublist
res = []
for values in b:
res.append({a[i]: values[i] for i in range(len(a))}) # Create a dictionary and append it to the result list
print(res)
Output
[{'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:
- for loop iterates over each sublist in b and a dictionary comprehension is used to pair each key from a with the corresponding value in the sublist.
- Each generated dictionary is appended to the list res, which accumulates all the dictionaries corresponding to the sublists in b.