简体   繁体   English

迭代多个列表并将其用作增值字典

[英]iterate over multiple list and use it as a value growing dictionary

I have 2 lists of the same size: 我有2个相同大小的列表:

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. 我想迭代2个列表,并以动态方式将其数据作为放入字典中。

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? 既然有“n”个事件desc ,有没有办法制作一个灵活的字典,它会根据列表大小增长?

Note: each dictionary inside a list is of fixed size. 注意:列表中的每个字典都是固定大小的。
ie each dictionary have only 2 keys- key1 and key2. 即每个字典只有2个键 - key1和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 ? 根据列表大小动态增长key1key2的最佳方法是什么?

Edit 1: Assume that there is only 1 "outer_key" and it has only 1 value- which is a list. 编辑1:假设只有1个“outer_key”,它只有1个值 - 这是一个列表。 And list has "n" number of dictionaries. 列表中有“n”个字典。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM