简体   繁体   English

如何创建一个可以解释未知密钥的字典

[英]How to create a dict that can account for unknown keys

I have a dict like this: dict_1 = {'a': 1, 'b': 2, 'c' : 3} . 我有这样的字典: dict_1 = {'a': 1, 'b': 2, 'c' : 3} I have a list of dict keys like list_1 = ['a', 'b', 'c', '*'] , where the * could be any value. 我有一个dict键列表,如list_1 = ['a', 'b', 'c', '*'] ,其中*可以是任何值。 I would like to create a dict that can handle * and assign it a value of 0 我想创建一个可以处理*并为其赋值为0的字典

Any ideas if this is possible? 任何想法,如果这是可能的?

Why don't you just use the standard dict.get method? 你为什么不使用标准的dict.get方法?

If you use d.get(key, 0) instead of d[key] it will give you the behaviour you want. 如果使用d.get(key, 0)而不是d[key] ,它将为您提供所需的行为。

Example: 例:

dict_1 = {'a': 1, 'b': 2, 'c' : 3}
dict_1.get('a', 0)    # returns 1
dict_1.get('Z', 0)    # returns 0

You seem to be describing python's inbuilt defaultdict . 你似乎在描述python的内置defaultdict

In your example, you could do the following; 在您的示例中,您可以执行以下操作;

from collections import defaultdict

dict_1 = defaultdict(lambda: 0)
dict_1["a"] = 1

print(dict_1["a"])  # will print 1 as that's what is set.
print(dict_1["any key"])  # will print 0, as it hasn't been set before.

Because you want a default of 0 specifically, you could also use defaultdict(int) as int() returns 0 . 因为您希望默认值为0 ,所以您也可以使用defaultdict(int)因为int()返回0

# if key not in dict_1 will print 0
for key in list_1:
    print(dict_1.get(key, 0))

You can create the new dictionary for your requirement in following way: 您可以通过以下方式为您的需求创建新词典:

dict_1 = {'a': 1, 'b': 2, 'c' : 3}
list_1 = ['a', 'b', 'c', '*']
# new dictonay with default value 0 for non-existing key in `dict_1`
new_dict = {l: dict_1.get(l, 0) for l in list_1}

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

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