【问题标题】:Merge two dictionaries with keys only from the first dict仅将两个字典与第一个字典中的键合并
【发布时间】:2021-03-30 04:03:55
【问题描述】:

我想合并两个字典,以便生成的字典具有来自第一个字典的键和来自第一个和第二个字典的值。

>>> A = {'AB': 'a', 'A': 'a'}
>>> B = {'AB': 'b', 'B': 'b'}
>>> merge_left(A, B)
{'AB': 'b', 'A': 'a'}

这有点类似于用于合并数据库表的左外连接,其中一侧用作“基础”,另一侧与之比较。

这是每个键在结果字典中应具有的值的表格。

Possible Situations Key in A Key not in A
Key in B Use B's value Don't include
Key not in B Use A's value N/A

是否有函数 merge_left 或类似的函数返回上面的字典?

【问题讨论】:

    标签: python dictionary merge


    【解决方案1】:

    我使用dict.get's ability to return a default value 制作了一个相当短的merge_left 函数。这对第一个字典的key, value 对使用字典理解,并根据第二个字典检查它们。

    def merge_left(defaults, override):
        return {key, override.get(key, default) for key, default in defaults.items()}
    

    由于这个函数只是返回一个 dict-comprehension,你可以将它直接“内联”到你的代码中。

    >>> A = {'AB': 'a', 'A': 'a'}
    >>> B = {'AB': 'b', 'B': 'b'}
    >>> {k: B.get(k, a) for k, a in A.items()}
    {'AB': 'b', 'A': 'a'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-13
      • 2017-07-23
      • 1970-01-01
      • 2019-05-16
      • 2018-08-23
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多