美文网首页
Python 技巧: 如何用一行代码合并两个字典?

Python 技巧: 如何用一行代码合并两个字典?

作者: DejavuMoments | 来源:发表于2018-12-24 15:23 被阅读7次

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place.

>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{'a': 1, 'b': 10, 'c': 11}

How can I get that final merged dict in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I'm looking for as well.)

For dictionaries x and y, z becomes a shallowly merged dictionary with values from y replacing those from x.

z = {**x, **y}
def merge_two_dicts(x, y):
    # start with x's keys and values    
    z = x.copy()
    # modifies z with y's keys and values & returns None
    z.update(y)
    return z

z = merge_two_dicts(x, y)

阅读原文:How to merge two dictionaries in a single expression?

相关文章

网友评论

      本文标题:Python 技巧: 如何用一行代码合并两个字典?

      本文链接:https://www.haomeiwen.com/subject/mwyshqtx.html