2017-01-03 61 views
-1

我是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'] 
+0

我想** ** respones1.json无效JSON。 – linusg

+0

编辑抱歉,关于那 – teddybear123

+0

固定对不起,再次 – teddybear123

回答

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)] 
+0

@linusg ** NO **不要覆盖内置列表构造函数! – DyZ

+0

当然不是!只是从OP的c'n'p ... – linusg

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 < 3.5使用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 
+0

不适用3.4:语法错误在'[{** x'。 (顺便说一句,没有必要调用'list()')。 – DyZ

+0

@DYZ,不能同意。 win32上的Python 3.5.2(v3.5.2:4def2a2901a5,Jun 25 2016,22:18:55)[MSC v.1900 64 bit(AMD64)] 输入“help”,“copyright”,“credits”或“许可”了解更多信息。数据1 = [{“qa”:“o”},{“qa”:“o”}] >>> data2 = [{“prod”:“x”},{“prod”:“ x]}] >>> >>> new_struct = [{** x,** y} for x,y in list(zip(data1,data2))] >>> print(new_struct) [{ 'qa':'o','prod':'x'},{'qa':'o','prod':'x'}] >>>' – RomanPerekhrest

+0

对不起, >>> new_struct = [{** x,** y} for x,y in list(zip(data1,data2))] 文件“”,第1行 new_struct = [{** x,** y } for x,y in list(zip(data1,data2))] ^ SyntaxError:无效语法 – DyZ