[英]How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys?
[英]How to create a dict that can account for unknown keys
我有这样的字典: dict_1 = {'a': 1, 'b': 2, 'c' : 3}
。 我有一个dict键列表,如list_1 = ['a', 'b', 'c', '*']
,其中*
可以是任何值。 我想创建一个可以处理*
并为其赋值为0
的字典
任何想法,如果这是可能的?
你为什么不使用标准的dict.get
方法?
如果使用d.get(key, 0)
而不是d[key]
,它将为您提供所需的行为。
例:
dict_1 = {'a': 1, 'b': 2, 'c' : 3}
dict_1.get('a', 0) # returns 1
dict_1.get('Z', 0) # returns 0
你似乎在描述python的内置defaultdict 。
在您的示例中,您可以执行以下操作;
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.
因为您希望默认值为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))
您可以通过以下方式为您的需求创建新词典:
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.