在python中合并dicts

时间:2011-09-14 04:09:03

标签: python arrays merge

我是python的新手。我有两个排序的数组(按键),我想合并。两个阵列都有一些公共密钥,有些在一个阵列中唯一存在。我想做一个外连接。

Array1 = {'key_1': 10, 'key_2': 14,..'key_m': 321}
Array2 = {'key_1': 15, 'key_2': 12..'key_m':2,..'key_n':34}

我想使用key_1..key_n ..

进行合并
Array3 = [[key_1',10,15],['key_2':14:12],..]

我的计算机上没有安装numpy软件包。我需要它来合并这个数组吗?编写代码的最佳方法是什么?感谢!!!

2 个答案:

答案 0 :(得分:2)

这个怎么样?

#!/usr/bin/env python
from itertools import chain

dict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
dict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}

dict3 = {}

# Go through all keys in both dictionaries
for key in set(chain(dict1, dict2)):

    # Find the key in either dictionary, using an empty
    # string as the default if it is not found.
    dict3[key] = [dict.get(key, "")
                  for dict in (dict1, dict2)]

print(dict3)

现在dict3列出了输入数组中的每个值。

或者如果您想要[[key, value, value], [key, value, value]...]格式:

#!/usr/bin/env python
from itertools import chain

dict1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
dict2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}

result = [[key] + [dict.get(key, "")
           for dict in (dict1, dict2)]
          for key in set(chain(dict1, dict2))]
result.sort()

print(result)

答案 1 :(得分:1)

您的Array3语法不正确。你可以尝试这样的事情:

>>> Array1 = {'key_1': 10, 'key_2': 14, 'key_m': 321}
>>> Array2 = {'key_1': 15, 'key_2': 12, 'key_m':2, 'key_n':34}
>>>
>>> Array3_dict = dict()
>>> for Array in (Array1, Array2):
...     for key, value in Array.items():
...         if not key in Array3_dict: Array3_dict[key] = list()
...         Array3_dict[key].append(value)
...
>>> Array3 = [ [ key ] + value for key, value in Array3_dict.items() ]
>>> Array3.sort()
>>> print Array3
[['key_1', 10, 15], ['key_2', 14, 12], ['key_m', 321, 2], ['key_n', 34]]
>>>