Zip Two dict包含Python中的列表

2024-09-25 06:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有n个dict,其中包含的值如列表所示

{"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"}

意味着zip或者我们可以分割dict键的基础,如果存在的话,只为每个键添加一个值。你知道吗


Tags: 列表data格式zip基础dictotherq3
1条回答
网友
1楼 · 发布于 2024-09-25 06:28:48

dict1.update(dict2)对你有用吗?这将用dict2中的值更新dict1。你知道吗

编辑:

这可能有用:

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']}}

相关问题 更多 >