压缩两个词典列表

时间:2017-01-03 21:51:27

标签: python json

我是Python的新手并尝试从json响应中创建一个新结构。两个json响应是来自2个环境但是具有相同长度和顺序的测试,只是不同的结果,为了简洁起见我简化了我的例子。

response1.json

[{"qa":"o"}, {"qa":"o"}]

response2.json

[{"prod":"x"}, {"prod": "x"}] 

create.py

with open('response1.json') as data_file:    
    data1 = json.load(data_file)

with open('response2.json') as data_file:    
    data2 = json.load(data_file)

#i want to be able to create a structure like this:
# [{"qa":"o", "prod":"x"},{"qa":"o", "prod":"x"}]

list = []

#This is wrong but was thinking that logic would be close to this.
for i in range(0,len(data1)):
   list[i]['qa'] = data1[i]['qa']

for i in range(0,len(data2)):
   list[i]['prod'] = data[i]['prod']

2 个答案:

答案 0 :(得分:1)

1) Python 3.5 解决方案使用zip()函数和字典解包运算符**

data1 = [{"qa":"o"},{"qa":"o"}]
data2 = [{"prod":"x"}, {"prod": "x"}]

new_struct = [{**x, **y} for x,y in zip(data1, data2)]
print(new_struct)

输出:

[{'qa': 'o', 'prod': 'x'}, {'qa': 'o', 'prod': 'x'}]

2) Python<使用dict.update()方法的 解决方案:

new_struct = []
for x,y in zip(data1, data2):
    x.update(y)
    new_struct.append(x)

print(new_struct) # will give the same output

答案 1 :(得分:0)

json_list = [dict(list(x[0].items()) + list(x[1].items())) for x in zip(data1,data2)]
print(json_list)

结果:

[{'qa': 'o', 'prod': 'x'}, {'qa': 'o', 'prod': 'x'}]

这是一个更优雅但可能效率更低的解决方案:

json_list = [dict(sum([list(y.items()) for y in x], [])) 
             for x in zip(data1,data2)]