Splitting a list of dictionaries into several lists of dictionaries

后端 未结 5 1589
刺人心
刺人心 2020-12-15 06:25

I\'ve been whacking away at this for a while to no avail... Any help would be greatly appreciated.

I have:

[{\'event\': 0, \'voltage\': 1, \'time\':         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 07:08

    dict_list = [{'event': 0, 'voltage': 1, 'time': 0},
    {'event': 0, 'voltage': 2, 'time': 1},
    {'event': 1, 'voltage': 1, 'time': 2},
    {'event': 1, 'voltage': 2, 'time': 3},
    {'event': 2, 'voltage': 1, 'time': 4},
    {'event': 2, 'voltage': 2, 'time': 5},
    ]
    
    import collections
    dol = collections.defaultdict(list)
    for d in dict_list:
       k = d["event"]
       dol[k].append(d)
    
    print dol
    

    if you know that your "event" keys are consecutive zero-based integers, you can use a list instead, but the extra complexity may not gain you anything.

    defaultdict was added in python 2.5, but the workaround for earlier versions is not hard (see Nick D's code).

提交回复
热议问题