我有一个单词出现词典和一个同义词词典。
单词出现词典示例:
word_count = {'grizzly': 2, 'panda': 4, 'beer': 3, 'ale': 5}
同义词词典示例:
synonyms = {
'bear': ['grizzly', 'bear', 'panda', 'kodiak'],
'beer': ['beer', 'ale', 'lager']
}
我想合并/重命名聚合字数统计字典为
new_word_count = {'bear': 6, 'beer': 8}
我想我会试试这个:
new_dict = {}
for word_key, word_value in word_count.items(): # Loop through word count dict
for syn_key, syn_value in synonyms.items(): # Loop through synonym dict
if word_key in [x for y in syn_value for x in y]: # Check if word in synonyms
if syn_key in new_dict: # If so:
new_dict[syn_key] += word_value # Increment count
else: # If not:
new_dict[syn_key] = word_value # Create key
但这行不通,new_dict 最终为空。另外,有没有更简单的方法来做到这一点?也许使用字典理解?
最佳答案
In [11]: {w: sum(word_count.get(x, 0) for x in ws) for w, ws in synonyms.items()}
Out[11]: {'bear': 6, 'beer': 8}
使用 collections.Counter
和 dict.get
:
from collections import Counter
ec = Counter()
for x, vs in synonyms.items():
for v in vs:
ec[x] += word_count.get(v, 0)
print(ec) # Counter({'bear': 6, 'beer': 8})
关于python - 聚合和重命名字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29460888/