![](/img/trans.png)
[英]Most pythonic way to update a dictionary value in a list of same dictionaries?
[英]Pythonic way for checking if value exists in dictionary of dictionaries and taking corresponding actions
我創建了一個字典詞典:
from collections import defaultdict
d = defaultdict(dict)
現在,我有了一些字符串(讓我們稱此集合A
),這些字符串具有一個字典(作為鍵)和與之相對應的整數(作為值)。 因此,以上數據結構完全對這些數據進行了建模。
現在,我要檢查字典中是否存在與A
中的鍵相對應的字符串。 如果它不存在,我想添加它並使其計數器為1
。 如果已經存在,我想增加計數器。
有pythonic的方法可以做到這一點嗎?
如果您擁有嵌套dict
的密鑰,則可以使用簡單的in
測試:
if somestring in d[key]:
d[key][somestring] += 1
else:
d[key][somestring] = 1
但您可以改用Counter
:
from collections import defaultdict, Counter
d = defaultdict(Counter)
d[key][somestring] += 1
像defaultdict
一樣, Counter
為丟失的鍵提供默認值,默認值為0
。
櫃台還有其他好處; .update()
遍歷一組字符串並手動為這些字符串增加一個計數器, .update()
將整個序列傳遞給.update()
方法以獲取適當的計數器:
d[key].update(sequence_of_strings)
Counter
就會為您算一算。
Counter
類是其他語言可以稱為“ Multi-Set”或“ Bag”類型的東西。 它們也支持有趣的比較和算術運算,請確保您已閱讀該類型的文檔。
正如Lev Levitsky指出的那樣,您想要使用Counter
。 例如,假設您具有以下字符串:
>>> the_strings = [
... ('a', ('the', 'strings', 'in', 'the', 'dict')),
... ('b', ('other', 'strings', 'in', 'the', 'dict', 'in', 'your', 'question'))
... ]
而要關聯到'a'
與該字計數的字典,你可以這樣做:
>>> my_dict = defaultdict(Counter)
>>> for key, strings in the_strings:
... my_dict[key].update(strings)
...
>>> my_dict['a']['the']
2
>>> my_dict['b']['in']
2
>>> my_dict['b']['question']
1
如果要增加單個值,可以執行以下操作:
>>> my_dict[the_string][the_word] += 1
或者,您可以使用update
方法自動增加可迭代對象中每個元素的數量:
>>> my_dict[the_string].update(iterable_of_elements)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.