将字典列表拆分为几个字典列表 [英] Splitting a list of dictionaries into several lists of dictionaries

查看:304
本文介绍了将字典列表拆分为几个字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了很长时间来解决这个问题,但无济于事……任何帮助都将是极大的 赞赏.

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

我有:

[{'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},
...]

我想按每个事件将字典列表拆分成这样(可以有很多事件):

and I want to split that list of dictionaries up per event like this (there can be arbitrarily many events):

list0 = [{'event': 0, 'voltage': 1, 'time': 0},
{'event': 0, 'voltage': 2, 'time': 1}]

list1 = [{'event': 1, 'voltage': 1, 'time': 2},
{'event': 1, 'voltage': 2, 'time': 3}]

list2 = [{'event': 2, 'voltage': 1, 'time': 4},
{'event': 2, 'voltage': 2, 'time': 5}]

listN = ...

推荐答案

使用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.

这会为您提供列表列表.如果您希望按事件将dict索引,如果您打算进行任何随机访问,则可能会使用dict(d).

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.

就构造一堆个人名单而言,我认为这是一个坏主意.除非您确切知道有多少您声称自己不打算使用它们,否则将有必要将它们创建为全局变量或使用eval(或以其他方式变黑).最好只是将它们保存在容器中.

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.

这篇关于将字典列表拆分为几个字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆