1
votes

I have 2 lists of the same size:

list1 = ['event1','event2']   #up to event-n
list2 = ['desc1', 'desc2']    #up to desc-n

I want to iterate over 2 lists and put their data as a value in to a dictionary in a dynamic way.

Expected output:

payload={
  "outer_key" : [ {
    "key1" : event1,
    "key2" : desc1 
  },
  {
    "key1" : event2,
    "key2" : desc2 
  }
 ]}   

Since there are "n" number of events and desc , is there a way to make a flexible dictionary, which will grow according to list size?

Note: each dictionary inside a list is of fixed size.
i.e. each dictionary have only 2 keys- key1 and key2.

My attempt :

import itertools
list1 = ['event1','event2']   #up to event-n
list2 = ['desc1', 'desc2']    #up to desc-n
for f, b in itertools.izip(list1, list2):
     payload={
     "outer_key" : [ {
     "key1" : f,
     "key2" : b
     }]}
print payload  

Obvious and actual output:

payload= {'outer_key': [{'key1': 'event2', 'key2':'desc2'}]}

What is the best way to dynamically grow key1 and key2 as per the list size ?

Edit 1: Assume that there is only 1 "outer_key" and it has only 1 value- which is a list. And list has "n" number of dictionaries.

1
What's "outer_key" ? - igon
outer_key is a fixed key and it's value is list of dictionary. - user3439895
Added the information in the question. - user3439895

1 Answers

3
votes

You are replacing the list with each iteration of the loop. Instead instantiate the list outside the loop and append to it inside.

import itertools
list1 = ['event1','event2']   #up to event-n
list2 = ['desc1', 'desc2']    #up to desc-n
payload = {
   "outer_key" : []
}
for f, b in itertools.izip(list1, list2):
     payload["outer_key"].append({"key1" : f, "key2" : b})
print payload