你也应该考虑寻找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