简体   繁体   中英

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} . I have a list of dict keys like list_1 = ['a', 'b', 'c', '*'] , where the * could be any value. I would like to create a dict that can handle * and assign it a value of 0

Any ideas if this is possible?

Why don't you just use the standard dict.get method?

If you use d.get(key, 0) instead of d[key] it will give you the behaviour you want.

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 .

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 .

# 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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