首页 > 解决方案 > 根据值聚合字典数组

问题描述

修订

data = [[{'type': 'low', 'count': 100}, {'type': 'medium', 'count': 45}, {'type': 'high', 'count': 5}],
[{'type': 'medium', 'count': 45}, {'type': 'high', 'count': 5}],
[{'type': 'low', 'count': 100}, {'type': 'medium', 'count': 45}]]

def unique_type(data):
    result = []
    type_list = []
    for x in data:
      for y in x: # arrays of dict
          if y['type'] not in type_list: #iterate through dicts in array
              type_list.append(y['type']) #if not type in list
              result.append({'type': y['type'], 'count': []}) #add type in list
    return result, type_list

result, type_list = unique_type(data)
empty_results = result
for arr in data:
    
    for num in range(0, len(type_list)):
        try:
            number = 0
            while number < len(type_list):
                print(f"{arr[num]['type']} == {result[number]['type']}")
                if arr[num]['type'] == result[number]['type']:
                    result[number]['count'].append(arr[num]['count'])
                    number += 1
                    break
                else:
                    number += 1
        except IndexError:
    
            # TODO need some way for evaluating if a key is missing from arr compared to result**
    
            print(f"Index Error{result[number]['type']}")
                
            result[number]['count'].append(float('nan'))

我得到的结果

[{'type': 'low', 'count': [100, nan, 100, nan]}, {'type': 'medium', 'count': [45, 45, 45]}, {'type': 'high', 'count': [5, 5]}]

期望的结果

[{'type': 'low', 'count': [100, nan, 100]}, {'type': 'medium', 'count': [45, 45, 45]}, {'type': 'high', 'count': [5, 5, nan]}]

Unique_type() 允许我遍历我的字典数组并创建一个唯一键数组

results 允许我构建我想要的字典数组

在遍历字典数组时,我想确保无论该键是否在结果中退出都有一个值。

原帖

嘿,伙计们,我正在建立一个对我来说有点棘手的模型

    a = {'type': 'Low', 'count': 184} 
    b = {'type': 'Low', 'count': 186} 
    c = {'type': 'Low', 'count': 97}

 

    new = [a,b,c]

### how do i accomplish below?

    result = {'type': low, 'count': [184, 186, 97]}

标签: python

解决方案


这是一个更通用的解决方案,假设您可以有几种类型:

from itertools import groupby

[{'type': k, 'count': [i['count'] for i in g]}
 for k,g in groupby(sorted(new, key=lambda d: d['type']),
                    key=lambda d: d['type'])
]

输入:

[{'type': 'Low', 'count': 184},
 {'type': 'Low', 'count': 186},
 {'type': 'Low', 'count': 97},
 {'type': 'High', 'count': 1000}]

输出:

[{'type': 'High', 'count': [1000]},
 {'type': 'Low', 'count': [184, 186, 97]}]

推荐阅读