如何按数十个字典分组列表

时间:2018-07-09 13:38:59

标签: python python-3.x

列表中有一些数据。我需要按时间范围分组数据。例如1,2,5,6-> 10天,13,11,16,18-> 20天。它是带有dict和dict的列表:

 ({'days':1, 'value':({some dict with data}), 
  {'days':13,'value':({some dict with data}),
  {'days':11,'value':({some dict with data}),
  {'days':23,'value':({some dict with data}),
  {'days':25,'value':({some dict with data}))

我需要按“天数”对数据进行分组,例如

 ({'range':10, 'value': ({'days':1, 'value':({some dict with data}), 
  {'range':20, 'value': ({'days':13,'value':{some dict with data},
                         {'days':11,'value':{some dict with data})
  {'range':30, 'value': ({'days':23,'value':{some dict with data},
                         {'days':25,'value':{some dict with data})
 )

2 个答案:

答案 0 :(得分:1)

提示:如果您有如下列表,则可以使用collections.defaultdict()

In [22]: lst = [{'days':1, 'value':3}, 
    ...:   {'days':13,'value':3},
    ...:   {'days':11,'value':3},
    ...:   {'days':23,'value':3},
    ...:   {'days':25,'value':3}]
    ...:   

In [23]: 

In [23]: d = defaultdict(list)

In [24]: for i in lst:
    ...:     d[(i['days']//10 + 1) * 10].append(i)
    ...:     
    ...:     

In [25]: d
Out[25]: 
defaultdict(list,
            {10: [{'days': 1, 'value': 3}],
             20: [{'days': 13, 'value': 3}, {'days': 11, 'value': 3}],
             30: [{'days': 23, 'value': 3}, {'days': 25, 'value': 3}]})

答案 1 :(得分:0)

pandas.cut是一个强大的工具,尤其是如果您有大量的词典。只需将输出调整为所需的任何形式即可。例如

df = pd.DataFrame(z)
df['cut'] = pd.cut(df.days, range(0,31,10))
df.groupby('cut').agg(list).T.to_dict()

输出

{Interval(0, 10, closed='right'): {'days': [1], 'value': [{}]},
 Interval(10, 20, closed='right'): {'days': [13, 11], 'value': [{}, {}]},
 Interval(20, 30, closed='right'): {'days': [23, 25], 'value': [{}, {}]}}