Python 技巧: 如何用一行代碼合并兩個字典?

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?

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,854評論 0 10
  • 由于熱天人們出汗較多,大量出汗可帶走大量的鉀元素,會使體內鉀離子過多喪失,造成低血鉀現象,會引起人體倦怠無力、頭昏...
    羅傲閱讀 310評論 0 1
  • 前言: 混在一大堆書里買回來的一本小書,《一個人的好天氣》。購買理由大概是獲得了某些獎項,看起來薄薄的,聊作打發(fā)時...
    她梔閱讀 757評論 2 0
  • 昨夜雨疏風驟,濃睡不消殘酒。試問卷簾人,卻道海棠依舊。知否,知否?應是綠肥紅瘦。 刮風又下雨,本來對今天的櫻花已經...
    Lithilda閱讀 337評論 0 1
  • 夜慢慢靜下來,站在窗前,看見玻璃上的自己,這個潛伏著各種情緒的自己,從年少到現在,有自信,有膽怯,有快樂!有貪婪!...
    默妍布語閱讀 197評論 0 0

友情鏈接更多精彩內容