【问题标题】:How To Merge Two Dictionaries With Common and Different Keys in Python?如何在 Python 中合并两个具有共同和不同键的字典?
【发布时间】:2021-08-28 03:18:13
【问题描述】:

我正在尝试制作一个将两个字典合并在一起的函数。当我搜索解决方案时,我可以找到仅适用于只有公共键或只有不同键的字典的解决方案,但不能同时解决这两种情况。

下面是我想要的示例。

输入

x = {"a": 91, "b": 102}
y = {"b": 8, "c": True}

输出

z = {"a": 91, "b": 110, "c": True}

【问题讨论】:

  • 是否可以添加字典的值

标签: python function dictionary merge key


【解决方案1】:

您可以使用dictionary comprehensiondict.get 方法和set union between dict.key objects 来做到这一点:

>>> z = {k: x[k] + y[k]
            if (k in x and k in y)
            else x.get(k) or y.get(k)
            for k in sorted(x.keys() | y.keys())}
>>> z
{'a': 91, 'b': 110, 'c': 1}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-11-26
    相关资源
    最近更新 更多