简体   繁体   English

如何使用默认字典更新python字典:另一个字典中给出的值对

[英]How to update a python dict with default key:value pairs given in another dict

Suppose a dictionary is expected to have certain keys present. 假设字典中存在某些键。 Is there a simple way of adding these specific keys with default values if they are missing? 如果缺少这些特定键和默认值,是否有一种简单的方法?

For example: 例如:

default_dict = {'name': '', 'height': 100, 'age': 20} 

d = {'name': 'James', 'age': 65}
d.set_defaults(default_dict)

would update the dictionary d to 会将字典d更新为

{'name': 'James', 'age': 65, 'height': 100}

where the original values of d are kept and only the missing keys are added. 保留d的原始值,仅添加缺少的键。

The default_dict should not be destroyed in the process. default_dict不应在此过程中销毁。

Create a copy of the defaults, and update it with d ; 创建默认值的副本,并使用d更新它; if all keys in d are strings, you can do so with one dict() call: 如果d中的所有键都是字符串,则可以通过一个dict()调用来实现:

d = dict(default_dict, **d)

For dictionaries with non-string keys, you'd use two steps: 对于带有非字符串键的字典,您可以使用两个步骤:

d = default_dict.copy()
d.update({'name': 'James', 'age': 65})

or you could use a loop to update d with any keys not present using dictionary views; 或者您可以使用循环使用字典视图中不存在的任何键更新d this is not as fast however: 但这不是那么快:

d = {'name': 'James', 'age': 65}
d.update((k, default_dict[v]) for k in default_dict.viewkeys() - d)

Replace viewkeys with keys in Python 3. 用Python 3中的keys替换viewkeys

If you are using Python 3.5 or newer, you can use similar syntax to create a new dictionary: 如果您使用的是Python 3.5或更高版本,则可以使用类似的语法来创建新字典:

d = {**default_dict, 'name': 'James', 'age': 65}

The key-value pairs of default_dict are applied first, followed by whatever new keys you set; 首先应用default_dict的键值对,然后再应用您设置的任何新键; these will override the old. 这些将覆盖旧的。 See PEP 448 - Additional Unpacking Generalizations in the 3.5 What's New documentation. 请参阅3.5新增功能文档中的PEP 448-其他拆包概述

Any of the methods creating a new dictionary can update an existing dictionary simply by wrapping in a dict.update() call. 任何创建新词典的方法都可以通过包装dict.update()调用来更新现有词典。 So the first could update d in-place with: 所以第一个可以用以下方法就地更新d

d.update(dict(default_dict, **d))

To update an existing dictionary, I might use the dictionary's setdefault method: 要更新现有字典,我可以使用字典的setdefault方法:

for key, value in dict_of_defaults.items():
    dict_maybe_without_defaults.setdefault(key, value)

If I was creating a new dictionary where I had a small number of keys, I'd probably do something more along the lines of the solution that was posted by Martijn. 如果要创建一个新的字典,其中只有少量的键,那么我可能会按照Martijn发布的解决方案进行更多操作。

You may consider using a collections.ChainMap to associate a fallback: 您可以考虑使用collections.ChainMap关联后备:

import collections

default_dict = {'name': '', 'height': 100, 'age': 20} 

d = collections.ChainMap({'name': 'James', 'age': 65},default_dict)

>>> d
ChainMap({'name': 'James', 'age': 65}, {'name': '', 'height': 100, 'age': 20})
>>> dict(d) #this flattens the map but isn't necessary for it to work
{'name': 'James', 'height': 100, 'age': 65}

Also note that since all mutating methods will only modify the first mapping default_dict is safe from pop or other methods. 另请注意,由于所有变异方法只会修改第一个映射,因此default_dictpop或其他方法是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM