How do I merge dictionaries together in Python?

后端 未结 7 1766
无人及你
无人及你 2020-12-04 17:05
d3 = dict(d1, **d2)

I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I woul

相关标签:
7条回答
  • 2020-12-04 18:01

    Starting in Python 3.9, the operator | creates a new dictionary with the merged keys and values from two dictionaries:

    # d1 = { 'a': 1, 'b': 2 }
    # d2 = { 'b': 1, 'c': 3 }
    d3 = d2 | d1
    # d3: {'b': 2, 'c': 3, 'a': 1}
    

    This:

    Creates a new dictionary d3 with the merged keys and values of d2 and d1. The values of d1 take priority when d2 and d1 share keys.


    Also note the |= operator which modifies d2 by merging d1 in, with priority on d1 values:

    # d1 = { 'a': 1, 'b': 2 }
    # d2 = { 'b': 1, 'c': 3 }
    d2 |= d1
    # d2: {'b': 2, 'c': 3, 'a': 1}
    

    0 讨论(0)
提交回复
热议问题