【问题标题】:merging dicts in python在python中合并字典
【发布时间】:2011-11-16 16:34:33
【问题描述】:

我是 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 包。我需要它来合并这个数组吗?对此进行编码的最佳方法是什么?谢谢!!!

【问题讨论】:

  • 它们对我来说就像字典!
  • 首先,这些是字典,而不是数组。其次,字典不能按照您希望的方式在 Array3 中构建。它们只能在 key:value pairs 中。
  • Python 的“数组”可以是字典(如哈希表)或列表(如序列)。见wellho.net/solutions/…

标签: python arrays merge


【解决方案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]]
>>>

【讨论】:

  • 谢谢。最后一个元素应该看起来像 ['key_n','',34]..is 是一个 n × 3 数组
  • 使用Array3_dict = defaultdict(list) 这样就不需要if not key 部分。
【解决方案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)

【讨论】:

  • 如果字典中有None的值怎么办?您在第二个get 之后也缺少一个括号,如果您不介意不那么明确的话,您可以只使用chain(array1, array2)
  • 在对另一个答案的评论中,他说如果字典中没有空值,他想要一个空值,所以你可能想要append(dict.get(key, ''))
  • @Brendan Long - 如何使数组的最后一个元素看起来像 ['key_n','',34]?谢谢..
  • @papu - 给你(第二个代码 sn-p)。我认为使用None 来表示不存在的值而不是空字符串会更加Pythonic。
猜你喜欢
  • 2011-01-22
  • 1970-01-01
  • 2020-11-28
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 2022-12-26
相关资源
最近更新 更多