Python Tricks - Dictionary Tricks(4)

So Many Ways to Merge Dictionaries

Have you ever built a configuration system for one of your Python programs? A common use case for such systems is to take a data structure with default configuration options, and then to allow the defaults to be overridden selectively from user input or some other config source.

I often found myself using dictionaries as the underlying data structure for representing configuration keys and values. And so I frequently needed a way to combine or to merge the config defaults and the user overrides into a single dictionary with the final configuration values.

Or, to generalize: sometimes you need a way to merge two or more dictionaries into one, so that the resulting dictionary contains a combination of the keys and values of the source dicts.

In this chapter I’ll show you a couple of ways to achieve that. Let’s look at a simple example first so we have something to discuss. Imagine you had these two source dictionaries:

>>> xs = {'a': 1, 'b': 2}
>>> ys = {'b': 3, 'c': 4}

Now, you want to create a new dict zs that contains all of the keys and values of xs and all of the keys and values of ys. Also, if you read the example closely, you saw that the string 'b'appears as a key in both dicts—we’ll need to think about a conflict resolution strategy for duplicate keys as well.

The classical solution for the “merging multiple dictionaries” problem in Python is to use the built-in dictionary update() method:

>>> zs = {}
>>> zs.update(xs)
>>> zs.update(ys)

If you’re curious, a naive implementation of update() might look something like this. We simply iterate over all of the items of the right-hand side dictionary and add each key/value pair to the left-hand side dictionary, overwriting existing keys as we go along:

def update(dict1, dict2):
  for key, value in dict2.items():
    dict1[key] = value

This results in a new dictionary zs which now contains the keys defined in xs and ys:

>>> zs
>>> {'c': 4, 'a': 1, 'b': 3}

You’ll also see that the order in which we call update() determines how conflicts are resolved. The last update wins and the duplicate key 'b' is associated with the value 3 that came from ys, the second source dictionary.

Of course you could expand this chain of update() calls for as long as you like in order to merge any number of dictionaries into one. It’s a practical and well-readable solution that works in Python 2 and Python 3.

Another technique that works in Python 2 and Python 3 uses the dict() built-in combined with the **-operator for “unpacking” objects:

>>> zs = dict(xs, **ys)
>>> zs
{'a': 1, 'c': 4, 'b': 3}

However, just like making repeated update() calls, this approach only works for merging two dictionaries and cannot be generalized to combine an arbitrary number of dictionaries in one step.

Starting with Python 3.5, the **-operator became more flexible. So in Python 3.5+ there’s another—and arguably prettier—way to merge an arbitrary number of dictionaries:

>>> zs = {**xs, **ys}

This expression has the exact same result as a chain of update() calls. Keys and values are set in a left-to-right order, so we get the same conflict resolution strategy: the right-hand side takes priority, and a value in ys overrides any existing value under the same key in xs. This becomes clear when we look at the dictionary that results from the merge operation:
右侧的字典有更高的优先级。

>>> zs
>>> {'c': 4, 'a': 1, 'b': 3}

Personally, I like the terseness of this new syntax and how it still remains sufficiently readable. There’s always a fine balance between verbosity and terseness to keep the code as readable and maintainable as possible.

In this case, I’m leaning towards using the new syntax if I’m working with Python 3. Using the **-operator is also faster than using chained update() calls, which is yet another benefit.

Key Takeaways
  • In Python 3.5 and above you can use the **-operator to merge multiple dictionary objects into one with a single expression, overwriting existing keys left-to-right.
  • To stay compatible with older versions of Python, you might want to use the built-in dictionary update() method instead.
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,230评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,261评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,089评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,542评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,542评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,544评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,922评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,578评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,816评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,576评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,658评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,359评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,937评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,920评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,859评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,381评论 2 342

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,279评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,355评论 0 23
  • 函数调用 Built-in Functions abs(x) Return the absolute value ...
    叫我七夜阅读 1,159评论 0 0
  • 夜卧听雨落,思秋至 晨起看花调,悲几许 立于凸起的田埂之上 放眼一片金黄 闻到了喜悦的气息 偶有几只鸟儿经过 衔起...
    月上阅读 319评论 0 2
  • 原来我一直遵守的人生信条,别人都不在乎了。都在变化。我本质不是安分的人,我终于有了一个学习目标,shuishuai...
    810eb92ed6da阅读 117评论 0 0