【问题标题】:Pythonic way of merging 2 lists of dicts based on common keys基于公共键合并2个字典列表的Pythonic方式
【发布时间】:2018-12-05 22:12:16
【问题描述】:

我有 2 个字典列表:

dict1 = [{"a":1, "b":2, "c":1295}, {"a":2, "b":5, "c":6274}, {"a":3, "b":1, "c":5337}]

dict2 = `[{"a":1, "b":2, "d":1884}, {"a":2, "b":5, "d":2049}, {"a":3, "b":3, "d":1086}]

第一个dicts列表有键"a""b""c",而第二个列表有键"a""b""d"

我想创建一个包含所有 4 个键的合并字典列表。只有"a""b" 值相等的字典需要合并。

预期的结果如下所示:

[{"a":1, "b":2, "c":1295, "d":1884}, {"a":2, "b":5, "c":6274, "d":2049}]

我正在寻找一种 Python 风格的方法。

【问题讨论】:

  • 订单是否符合您的示例。就像您是否总是尝试将dict1[i]dict2[i] 匹配?
  • 暂时就是这样。

标签: python python-3.x python-2.7 list dictionary


【解决方案1】:

假设两个列表中的 merging-candidates 是来自同一位置的 dicts,您可以将列表压缩在一起,使用列表理解并使用 **-syntax idiom 来合并两个 dicts。

>>> dicts1 = [{"a":1, "b":2, "c":1295}, {"a":2, "b":5, "c":6274}, {"a":3, "b":1, "c":5337}]
>>> dicts2 = [{"a":1, "b":2, "d":1884}, {"a":2, "b":5, "d":2049}, {"a":3, "b":3, "d":1086}]
>>> 
>>> [{**d1, **d2} for d1, d2 in zip(dicts1, dicts2) if all(d1[k] == d2[k] for k in ('a', 'b'))]
[{'a': 1, 'b': 2, 'c': 1295, 'd': 1884},
 {'a': 2, 'b': 5, 'c': 6274, 'd': 2049}]

奖金pandas解决方案:

>>> df1 = pd.DataFrame(dicts1)
>>> df2 = pd.DataFrame(dicts2)
>>> 
>>> df1
   a  b     c
0  1  2  1295
1  2  5  6274
2  3  1  5337
>>> 
>>> df2
   a  b     d
0  1  2  1884
1  2  5  2049
2  3  3  1086
>>> 
>>> pd.merge(df1, df2, on=['a', 'b']).to_dict(orient='records')
[{'a': 1, 'b': 2, 'c': 1295, 'd': 1884},
 {'a': 2, 'b': 5, 'c': 6274, 'd': 2049}]

【讨论】:

    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 2016-04-07
    • 2011-06-03
    • 2017-06-02
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多