我有一个类似结构的字典列表:
[
{'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/