怎样合并字典最符合 Python 语言习惯

怎样合并字典最符合 Python 语言习惯

不过由于译文已经404了,所以在此提供由Wayback Machine创建的网页快照(当然有能力的话也可以阅读英文原文)

http://web.archive.org/web/20190623000745/http://codingpy.com/article/the-idiomatic-way-to-merge-dicts-in-python/

(快照创建日期:2019-06-23)


总结一下原文的观点:

如果你在使用Python 3.5以上的版本,以下这种方法是最Pythonic且最高效的:

# 将字典user的内容合并到字典defaults中 并返回一个新的字典context 
context = {**defaults, **user}

非常直观明了,难道不是吗?

如果你还在使用Python 3.5之前的版本,那你就需要从原文中找到一个最适合的方案了。


如果你在使用Python 3.9以上的版本,那么还有一种更加Pythonic的方法:

defaults = dict(who="someone", where="somewhere")
params = dict(where="our town", when="today")
defaults | params
# return: {'who': 'someone', 'where': 'our town', 'when': 'today'}

摘自:How Python 3.9 fixed decorators and improved dictionaries