【发布时间】:2015-06-10 05:42:17
【问题描述】:
我有一个单词出现词典和一个同义词词典。
单词出现词典示例:
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 最终为空。另外,有没有更简单的方法来做到这一点?也许使用字典理解?
【问题讨论】:
标签: python python-3.x dictionary key rename