Splitting a list of dictionaries into several lists of dictionaries

后端 未结 5 1590
刺人心
刺人心 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

    use defaultdict

    import collections
    
    result = collections.defaultdict(list)
    
    for d in dict_list:
        result[d['event']].append(d)
    
    result_list = result.values()        # Python 2.x
    result_list = list(result.values())  # Python 3
    

    This way, you don't have to make any assumptions about how many different events there are or if there are any events missing.

    This gives you a list of lists. If you want a dict indexed by event, I would probably use dict(d) if you plan on doing any random access.

    As far as constructing a bunch of individual lists, I think that that's a bad idea. It will necessitate creating them as globals or using eval (or getting hacky in some other way) unless you know exactly how many there are going to be which you claim not to. It's best to just keep them in a container.

提交回复
热议问题