Reputation: 11
list1 = [a,b,c]
list2 =[d,e,f]
list3 = [g,h,j]
new_list = []
for i in list1:
new_dev ={'key1':'value1','key2':'value2','key3':i}
new_list.append(new_dev)
I want to perform the same action as above and iterate over list2
and list3
and there values should reflect in key1
from list1
and key2
from list2
. Thus after appending into the empty list 'new_list'
, it will have three dictionaries as elements. Please help me resolving this.
Think of the elements of the list as the values in the dictionary and so for key1
the values should be from list1
and for key2
the values should be from list2
and so on. Thus we should be getting a list with three dictionaries as elements in the "new_list"
.
Upvotes: 1
Views: 138
Reputation: 19307
You can do this with a one-liner using two zip
s in a list comprehension -
list1 = ['a','b','c']
list2 = ['d','e','f']
list3 = ['g','h','j']
keys = ['key1','key2','key3'] #<----
out = [dict(zip(keys,i)) for i in zip(list1, list2, list3)] #<----
print(out)
[{'key1': 'a', 'key2': 'd', 'key3': 'g'},
{'key1': 'b', 'key2': 'e', 'key3': 'h'},
{'key1': 'c', 'key2': 'f', 'key3': 'j'}]
zip(list1, list2, list3)
the 3 lists together which combines the first, second, third and nth elements of each list together into respective tuples.[i for i in (list1, list2, list3)
zip(keys,i)
, which gives you something like (key1, a), (key2, d), (key3, g)
for each tuple.dict
using dict(zip(keys,i)
which converts the first elements of each tuple as key and second elements of each tuple as value.Upvotes: 0
Reputation: 1367
You can use zip()
to merge the lists, and then take three elements from the merged list at each iteration step like so:
list1 = ['a', 'b', 'c']
list2 = ['d', 'e', 'f']
list3 = ['g', 'h', 'j']
new_list = []
for (i, j, k) in zip(list1, list2, list3):
new_dev ={'key1': i, 'key2': j, 'key3': k}
new_list.append(new_dev)
print(new_list)
>>> [{'key1': 'a', 'key2': 'd', 'key3': 'g'}, {'key1': 'b', 'key2': 'e', 'key3': 'h'}, {'key1': 'c', 'key2': 'f', 'key3': 'j'}]
Upvotes: 1