Check if a given key exists in a dict
要檢查 dictionary 是否存在索引值
直接查會直接 KeyError
>>> d = {}
>>> d['a']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'a'
這時就要靠 collections.defaultdict(default_factory)>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['a']
0
再回到檢查 dictionary 是否存在索引值的地方from collections import defaultdict
s = 'mississippi'
my_dict = defaultdict(int)
for key in s:
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
print(my_dict)
結果defaultdict(, {'m': 1, 'i': 4, 's': 4, 'p': 2})
參考資料 :
https://docs.python.org/3/library/collections.html#defaultdict-examples
https://stackoverflow.com/questions/473099/check-if-a-given-key-already-exists-in-a-dictionary-and-increment-it
0 意見:
張貼留言