你也應該考慮尋找collections.defaultdict
和collections.Counter
:
一個defaultdict
將在缺省值自動填充,一個Counter
是dict
專門爲計數:
from collections import defaultdict
from collections import Counter
sent = [[('Merger', 'NOUN'), ('proposed', 'VERB')], [('Wards', 'NOUN'), ('protected', 'VERB')]]
dicts = defaultdict(Counter) # A default dictionary of Counters
for x in sent:
for y in x:
dicts[y[0]][y[1]] += 1
print(dicts)
# defaultdict(<class 'collections.Counter'>, {'Merger': Counter({'NOUN': 1}), 'proposed': Counter({'VERB': 1}), 'Wards': Counter({'NOUN': 1}), 'protected': Counter({'VERB': 1})})
如果您想跳過Counter
,你可以只使用一個返回defaultdict(int)
和不帶參數的輔助功能:
from collections import defaultdict
def int_dict():
return defaultdict(int)
dicts = defaultdict(int_dict)
for x in sent:
for y in x:
dicts[y[0]][y[1]] += 1
print(dicts)
# defaultdict(<function a at 0x112c48048>, {'Merger': defaultdict(<class 'int'>, {'NOUN': 1}), 'proposed': defaultdict(<class 'int'>, {'VERB': 1}), 'Wards': defaultdict(<class 'int'>, {'NOUN': 1}), 'protected': defaultdict(<class 'int'>, {'VERB': 1})})
來源
2017-03-03 00:46:47
pml
你從高聲望的人兩次快速的答案,但我努力理解的'類型的字典用處[Y [0] ] [y [1]] + = 1'。你期待什麼輸出? – roganjosh
@roganjosh嗨,我想創建一個嵌套的字典。所以它會是{Merger:{Noun:1}} –
我認爲它實際上解決了TerryA的編輯答案。它只是看起來不正確,我想知道是否有迂迴的事情發生。 – roganjosh