user20880625
user20880625

Reputation: 11

How to iterate over a list and enter those values in a dictionary in Python?

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

Answers (2)

Akshay Sehgal
Akshay Sehgal

Reputation: 19307

You can do this with a one-liner using two zips 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'}]

EXPLANATION

  1. First you zip(list1, list2, list3) the 3 lists together which combines the first, second, third and nth elements of each list together into respective tuples.
  2. Next, you iterate through these tuples using [i for i in (list1, list2, list3)
  3. After that you zip this tuple, with the list of keys using zip(keys,i), which gives you something like (key1, a), (key2, d), (key3, g) for each tuple.
  4. Finally you convert this zip object to a 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

The Photon
The Photon

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

Related Questions