使用Python添加JSON属性?

时间:2015-01-05 00:05:38

标签: python json

我正在尝试使用Python组合数据。举个例子,我想结合

[{'foo': 'something'}, {'foo': 'something else'}, {'foo': 'something else'}]

[{'bar': 'else'}, {'bar': 'else else'}, {'bar': 'else else'}]

这样的事情:

[{'foo: 'something', 'bar': 'else'}, {'foo': 'something else', 'bar': 'else else'}, {'foo': 'something else', 'bar': 'else else'}]

这可以用Python吗?

2 个答案:

答案 0 :(得分:1)

您需要做的就是为每两个输入词典生成一个新词典。使用zip()生成对:

result = [dict(a, **b) for a, b in zip(first, second)]

其中firstsecond是您的输入列表。 dict()创建现有字典的副本,但**b语法是添加其他键的一个技巧。

答案 1 :(得分:1)

结果将在 a

a = [{'foo': 'something'}, {'foo': 'something else'}, {'foo': 'something else'}] 
b = [{'bar': 'else'}, {'bar': 'else else'}, {'bar': 'else else'}]
for i,j in zip(a,b):
     i.update(j)
print a