![](/img/trans.png)
[英]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.