2016-01-13 36 views
0

多个JSON我有一个包含多个JSON字符串这样如何合并在python

a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}] 

我想这些合并到这样

a = [{"name": "Alex","Age": 25,"Address": "16, Mount View"}] 

单个阵列我已经尝试了列表使用jsonmerge,但没有运气,使用head' and基准值时工作正常。

有人能帮我一个这个。

我也通过堆栈一个类似的问题了,但它显示了合并单独JSON,但在列表不是JSON How to merge two json

+0

的[我如何合并类型的字典列表到一个单一的字典?(可能的复制http://stackoverflow.com/questions/3494906/how-do-i-merge-a- list-of-dicts-into-a-single-dict) – taleinat

+0

这与JSON没有任何关系,因为在这一点上,您只需拥有一个Python字典对象列表。关于如何将一系列词典合并在一起已经有很多答案,例如[这个SO问题的答案](http://stackoverflow.com/questions/3494906/how-do-i-merge-a-list-of-dicts-into-a-single-dict)。 – taleinat

回答

2

首先,这些蟒蛇类型的字典

[{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}] 

你可以调用JSON。转储它们并将它们变成“json字符串”。

2,你可以使用字典更新方法

a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}] 
d = {} 
for small_dict in a: 
    d.update(small_dict) 
print(d) # Yay! 
a = [d] 

被警告!如果您有重复的钥匙,他们将覆盖互相

还采取“ChainMap”一看

https://docs.python.org/3/library/collections.html#collections.ChainMap

+0

有没有办法取代重复键? –

+0

使用反向列表会给你 - a [:: - 1](它只是从末尾开始替换开始:)) –

+0

如何使用反向列表,我应该使用它作为'for small_dict in -a: ' –

1

为了增加@yoav glazner的答案,如果你是Python的3.3+,你可以使用ChainMap

>>> from collections import ChainMap 
>>> a = [{"name": "Alex"},{"Age": 25},{"Address": "16, Mount View"}] 
>>> dict(ChainMap(*a)) 
{'name': 'Alex', 'Age': 25, 'Address': '16, Mount View'} 

查看更多关于ChainMap使用案例在这里: