python - 在 python 中打包字典列表

标签 python list dictionary pandas group-by

我有一个类似结构的字典列表:

[
    {'state': '1', 'city': 'a'},
    {'state': '1', 'city': 'b'},
    {'state': '2', 'city': 'c'},
    {'state': '2', 'city': 'd'},
    {'state': '3', 'city': 'e'}
]

我想这样打包:

[
    {'state': '1', 'cities': ['a', 'b']},
    {'state': '2', 'cities': ['c', 'd']},
    {'state': '3', 'cities': ['e']}
]

我有一个两步方法,可行,但速度非常慢(我的列表超过 10000 个项目,而且我的字典很复杂):

def pack(iterable):

    # step 1: lists -> super slow ! contains duplicates
    listed = [{'state': i['state'],
              'cities': [c['city'] for c in iterable if c['state']==i['state']]}
              for i in iterable]

    # step 2: remove duplicates
    packed = [l for n, l in enumerate(listed) if not l in listed[n+1:]]

    return packed

有什么优化建议吗?

PS:欢迎对帖子标题提出建议。

2014/09/26编辑:我刚刚发现pandas非标准库在这种情况下很有帮助。

下面我的 self 回答中有更多示例。

最佳答案

state_merged = {}
for s in states:
    state_merged.setdefault(s['state'], []).append(s['city'])

states = [{'state':k, 'cities':v} for k, v in state_merged.iteritems()]

如果您使用的是 python 3.0,请使用 state_merged.items() 而不是 state_merged.iteritems()

关于python - 在 python 中打包字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25064197/

相关文章:

将线性链表转换为循环链表

string - groovy eval string 列出包含字符串的列表

c# - 将查询投影到匿名 Dictionary<string,int>

java - 在 map 中,按一个字段排序并按另一个字段删除元素?

python - 使用 Python 连接到 Access 2013 : Data source name not found

python - 类型错误 : tan^-1 (tan inverse) of the ratio of two dataframe column

python - Numpy python 中的数组索引

python - 从列表中删除标点符号

python - 删除字典键中的空格

python - 非关系数据存储的用例是什么?