【问题标题】:add values of dictionary based of matching of keys and list elements根据键和列表元素的匹配添加字典值
【发布时间】:2019-07-16 12:17:14
【问题描述】:

我有一个字典列表:

[{
 'doc1': {'hyundai': 12,
   'mercedez': 34,
   'bugatti': 2,
   'honda': 19},
 'doc2': {'tennis': 20,
   'wimbledon': 11,
   'nadal': 57}, 
 'doc3':{'world': ,
   'politics': 8,
   'obama': 7,
   'america': 4,
   'summit': 14,
   'budget': 17,
   'germany': 22
}}]

和单词列表l= ['trump','mercedez','wimbledon','nadal','hyundai','tennis']

我只想将列表元素与字典的键匹配,并获得其值的总和,并与最高总和一起排序,如果没有元素匹配,则对应键的总和将为零。

预期为,

new_dict={'doc2':88,'doc1':46,'doc3'=0}

【问题讨论】:

  • 如果你的new_list 只包含一个字典,为什么它甚至是一个列表?当您的输入没有时,为什么它有 doc3 的条目?您希望对列表或包含的字典进行排序吗?
  • @MisterMiyagi doc3 的值为 0,因为没有列表元素与 doc3 的键匹配。因此,总和为零。是的,我想要对字典进行排序。希望你明白了 :)
  • 我不明白你为什么会有一本字典的列表?
  • 最终的字典应该包含键作为文档,值将是所有匹配值的总和,最后我希望它根据最高总和进行排序。@
  • 这听起来一点也不坏。我已经写好了答案,但我想看看你的尝试

标签: python arrays python-3.x dictionary


【解决方案1】:

您可以使用.items() 进行迭代,

然后以相同的方式迭代内部字典。

像这样:

d_list = [{'doc1': {'hyundai': 12,
                    'mercedez': 34,
                    'bugatti': 2,
                    'honda': 19},
           'doc2': {'tennis': 20,
                    'wimbledon': 11,
                    'nadal': 57},
           'doc3': {'world': 0,
                    'politics': 8,
                    'obama': 7,
                    'america': 4,
                    'summit': 14,
                    'budget': 17,
                    'germany': 22}}]

l = ['trump', 'mercedez', 'wimbledon', 'nadal', 'hyundai', 'tennis']


result_d = {}
for doc_name, inner_dict in d_list[0].items():
    result_d[doc_name] = sum(v for k,v in inner_dict.items() if k in l)

new_list = [result_d]

print(new_list)

输出:

[{'doc1': 46, 'doc2': 88, 'doc3': 0}]

【讨论】:

    【解决方案2】:

    试试这个,

    In [131]: A = [{'doc1': {'hyundai': 12, 'mercedez': 34, 'bugatti': 2, 'honda': 19},
         ...:       'doc2': {'tennis': 20, 'wimbledon': 11, 'nadal': 57},
         ...:       'doc3': {'world': 0, 'politics': 8, 'obama': 7, 'america': 4, 'summit': 14, 'budget': 17, 'germany': 22}}]
    
    In [132]: B = ['trump', 'mercedez', 'wimbledon', 'nadal', 'hyundai', 'tennis']
    
    In [133]: dict_comprehension = {key: sum([value.get(b, 0) for b in B]) for key, value in A[0].items()}
    
    In [134]: result = dict(sorted(dict_comprehension.items(), key=lambda x: x[1], reverse=True))
    
    In [135]: result
    Out[135]: {'doc2': 88, 'doc1': 46, 'doc3': 0}
    

    我使用 dict comprehensions 得到了您预期的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多