python - 聚合和重命名字典中的键

标签 python python-3.x dictionary key rename

我有一个单词出现词典和一个同义词词典。

单词出现词典示例:

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 最终为空。另外,有没有更简单的方法来做到这一点?也许使用字典理解?

最佳答案

使用字典理解,sumdict.get :

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.Counterdict.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/

相关文章:

python - 无法从 JSON 反序列化 PyMongo ObjectId

Python 异步事件循环。完成异步任务后永远运行循环

python - 用 Python 3 编写 Cocoa 应用程序

Python 使用理解合并字典键和值

python - 访问字典模块项目

java - 为什么 Map 不是 "true"集合?

python - 当我的表中也有 NaN 值时,我可以使用什么来代替 .loc?

python - Pandas Groupby 累计金额

python - 散列 Numpy 对象以进行缓存的快速方法

python-3.x - 使用 boto3 扫描 Dynamo DB 以获取字典数组