【问题标题】:Compare two list of dictionaries and use similar key to compute比较两个字典列表并使用相似的键来计算
【发布时间】:2020-05-16 01:27:23
【问题描述】:

我需要比较两个字典列表:

list_1 =
[
    { 
      'key1': {
                'growthScore': 6.7
    },
    { 
      'key2': {
                'growthScore': 9.2
    }
]
list_2 =
[
    { 
      'key1': {
                'growthScore': 7.8
    },
    { 
      'key2': {
                'growthScore': 5.6
    }
]
  • 遍历这两个列表。
  • 并比较相似的键并选择最高分。

输出:

[
    { 
      'key1': {
                'growthScore': 7.8
    },
    { 
      'key2': {
                'growthScore': 9.2
    }
]

【问题讨论】:

  • 所以..你试过吗?
  • 是的。这就是我现在对单个列表所做的: return max(list , key = lambda x : x.get('growthScore'),default = {})
  • 请从intro tour 重复how to askMRE。你所做的只是发布一个问题:没有问题,没有尝试的解决方案,没有问题输出。
  • 会的。谢谢。

标签: python list dictionary compare zip


【解决方案1】:

如果我正确理解了您的问题,这就是解决方案:

list_1 = [{'key1': {'growthScore': 6.7}},{'key2': {'growthScore': 9.2}}]
list_2 = [{'key1': {'growthScore': 7.8}},{'key2': {'growthScore': 5.6}}]

solution = []
for i in range(len(list_1)):
    for key in list_1[i].keys():
        if list_1[i][key]["growthScore"] > list_2[i][key]["growthScore"]:
            solution.append(list_1[i][key])
        else:
            solution.append(list_2[i][key])

print(solution)

PS:请明确您的问题,并确保为每个左括号 { 提供一个右括号 }

【讨论】:

  • 谢谢。这与 solution.append(list_1[i]) 的细微变化一起获得了整个项目。
  • 很高兴听到这个消息,如果对您有帮助,请标记答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
相关资源
最近更新 更多