【问题标题】:De-duplicating elements of dictionary based on conditions [Python]基于条件的去重字典元素[Python]
【发布时间】:2020-04-17 04:17:04
【问题描述】:

我有一本字典如下:

dict = {
'key-1': [('blue', '-20'), ('red', '-67')], 
'key-2': [('blue', '-77'), ('cyan', '-67'), ('white', '-57')],
'key-3': [('blue', '-39'), ('cyan , '-35'), ('purple', '-60')]
}

上面的字典包含带有元组的键(“颜色”,“权重”)。我想过滤列表,以便如果字典中的颜色重复,则应保留权重最高的元组,并且应从字典中弹出该颜色的所有其他出现。

在这种情况下,过滤后的字典应该如下所示:

filtered_dict = {
'key-1': [('blue', '-20'), ('red', '-67')], 
'key-2': [('white', '-57')],
'key-3': [('purple', '-60'), ('cyan', '-35')]
}

字典是使用颜色和权重动态生成的。我应该如何解决这个问题?

如有必要,可以更改形成字典的结构。

[编辑:权重为负数]

【问题讨论】:

    标签: python python-3.x dictionary data-science


    【解决方案1】:

    创建一个包含所有颜色-最大值键值对的 max_dict。然后遍历原始字典,将每个元组与 max_dict 进行比较。

    key_dict = {
    'key-1': [('blue', '20'), ('red', '67')], 
    'key-2': [('blue', '77'), ('cyan', '67'), ('white', '57')],
    'key-3': [('blue', '39'), ('cyan' , '35'), ('purple', '60')]
    }
    
    # create a max_dict including all the key-value pairs of color-maximum value
    max_dict = dict()
    
    for color_list in key_dict.values():
        for item in color_list:
            if item[0] not in max_dict.keys():
                max_dict.update({item[0]: int(item[1])})
            else:
                if int(item[1]) > max_dict[item[0]]:
                    max_dict.update({item[0]: int(item[1])})
    
    # create a list to hold all the updated list of tuples from the original dictionary
    list_of_values = []
    
    # sort through the original dictionary, comparing each tuple to the max_dict key-value pairs
    for color_list in key_dict.values():
        list_of_tuples = []
        for item in color_list:
            if int(item[1]) == max_dict[item[0]]:
                list_of_tuples.append(item)
        list_of_values.append(list_of_tuples)
    
    filtered_dict = dict(zip(key_dict.keys(), list_of_values))
    

    输出:

    >>> filtered_dict
    {'key-1': [('red', '67')], 'key-2': [('blue', '77'), ('cyan', '67'), ('white', '57')], 'key-3': [('purple', '60')]}
    

    【讨论】:

      【解决方案2】:

      您可以使用collections.defaultdict 构建包含每种颜色的所有最大权重的字典:

      from collections import defaultdict
      
      dic = {
          'key-1': [('blue', '-20'), ('red', '-67')], 
          'key-2': [('blue', '-77'), ('cyan', '-67'), ('white', '-57')],
          'key-3': [('blue', '-39'), ('cyan' , '-35'), ('purple', '-60')]
      }
      
      color_weight_groups = defaultdict(list)
      
      for lst in dic.values():
          for color, weight in lst:
              color_weight_groups[color].append(weight)
      
      max_weights = {k: max(map(int, v)) for k, v in color_weight_groups.items()}
      
      print(max_weights)
      

      看起来像这样:

      {'blue': -20, 'red': -67, 'cyan': -35, 'white': -57, 'purple': -60}
      

      然后创建一个新字典,将每个权重与最大权重进行比较:

      result = {
          k: [(color, weight) for color, weight in v if int(weight) == max_weights[color]]
          for k, v in dic.items()
      }
      
      print(result)
      

      这给出了这个过滤结果:

      {'key-1': [('blue', '-20'), ('red', '-67')], 'key-2': [('white', '-57')], 'key-3': [('cyan', '-35'), ('purple', '-60')]}
      

      【讨论】:

        猜你喜欢
        • 2016-04-07
        • 2022-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-07
        • 2019-06-20
        相关资源
        最近更新 更多