2013-11-22 65 views
-3

我有字典的n个包含值列表像邮编两个字典包含一个列表在Python

{"1":[{'q': ['Data'], 'q1': '110'}]} 

{"2":[{'q2':["other Data"], "q3" : "exp"},{'q2':["other Data2"], "q3" : "exp2"}]} 

我想以这种格式输出: -

{"1":[{'q': ['Data'], 'q1': '110'}],"2":[{'q2':["other Data"], "q3" : "exp"}]} 
{"2":{'q2':["other Data2"], "q3" : "exp2"} 

手段拉链,或者我们可以字典键的拆分基础,并为每个键添加一个值(如果存在)。

+0

所需输出缺少一些右括号,和你的数据结构已经足够混乱无错别字。 – askewchan

+0

@askewchan更新问题。 – Arpit

回答

1

是否dict1.update(dict2)对您有用?这将仅更新dict1dict2中的值。

编辑:

这可能会实现:

dicts=[] 
dicts.append({"1":[{'q': ['Data'], 'q1': '110'}]}) 
dicts.append({"2":[{'q2':["other Data"], "q3" : "exp"},{'q2':["other Data2"], "q3" : "exp2"}]}) 

a=[[{key: j} for key in d2 for j in d2[key]] for d2 in dicts ] 

nmax=max(len(x) for x in a) 

newdicts=[dict() for i in range(nmax)] 

for i in range(nmax):  
    for j in range(len(a)): 
     if i < len(a[j]):  
      newdicts[i].update(a[j][i]) 

for i in newdicts: 
    print i 

这给了我:

{'1': {'q': ['Data'], 'q1': '110'}, '2': {'q3': 'exp', 'q2': ['other Data']}} 
{'2': {'q3': 'exp2', 'q2': ['other Data2']}} 
+0

我有字典中的值列表,所以我想分裂在一个键中包含相同数量的值 – Arpit

相关问题