【问题标题】:Aggregating and Renaming Keys in Dictionary在字典中聚合和重命名键
【发布时间】: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


    【解决方案1】:

    使用字典理解,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})
    

    【讨论】:

      【解决方案2】:

      让我们稍微改变一下你的同义词词典。与其从一个词映射到其所有同义词的列表,不如从一个词映射到它的父同义词(即alebeer)。这应该会加快查找速度

      synonyms = {
                  'bear': ['grizzly', 'bear', 'panda', 'kodiak'],
                  'beer': ['beer', 'ale', 'lager']
                 }
      synonyms = {syn:word for word,syns in synonyms.items() for syn in syns}
      

      现在,让我们来制作你的聚合字典:

      word_count = {'grizzly': 2, 'panda': 4, 'beer': 3, 'ale': 5}
      new_word_count = {}
      for word,count in word_count:
          word = synonyms[word]
          if word not in new_word_count:
              new_word_count[word] = 0
          new_word_count[word] += count
      

      【讨论】:

      • 谢谢。这帮助我找到了原始代码中的错误。为了简洁起见,我使用了先前答案的字典理解。
      猜你喜欢
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多