Python 嵌套字典和列表的单词计数器
我有一本这样的字典:Python 嵌套字典和列表的单词计数器,python,dictionary,Python,Dictionary,我有一本这样的字典: d = {'name1': {'details': ['something', 'another thing',], 'groups': ['first', 'second'], }, 'name2': {'details': ['other details'], 'groups': ['first', 'third'], }} groups = ['first', 'second', 'third'] 下面是一个列表: d = {'name1':
d = {'name1': {'details': ['something',
'another thing',],
'groups': ['first', 'second'],
},
'name2': {'details': ['other details'],
'groups': ['first', 'third'],
}}
groups = ['first', 'second', 'third']
下面是一个列表:
d = {'name1': {'details': ['something',
'another thing',],
'groups': ['first', 'second'],
},
'name2': {'details': ['other details'],
'groups': ['first', 'third'],
}}
groups = ['first', 'second', 'third']
我想计算一下每组被提及的次数,并得到以下结果:
counted = {'first': 2, 'second':1, third:1}
我尝试过循环,但出现了各种错误。这样就可以了
import itertools
from collections import Counter
Counter(itertools.chain.from_iterable([x['groups'] for x in d.values()]))
输出
Counter({'first': 2, 'second': 1, 'third': 1})
您可以使用
列表理解:
from collections import Counter
print(Counter([i for v in d.values() for i in v["groups"]]))
# Counter({'first': 2, 'second': 1, 'third': 1})
试试这个:
d = {'name1': {'details': ['something',
'another thing',],
'groups': ['first', 'second'],
},
'name2': {'details': ['other details'],
'groups': ['first', 'third'],
}}
counted = {}
for names in d.keys():
for elements in d[names]["groups"]:
if elements not in counted.keys():
counted[elements] = 1
else:
counted[elements] += 1
print(counted)
您的组
列表不是列表。这是一个元组(列表)。@jarmod,谢谢-typo:)