[英]Create a sublist from list of dictionaries
I want to create a sublist from current list of dictionaries base on dictionary key.我想根据字典键从当前字典列表创建一个子列表。
My data:我的数据:
[{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]
Data which I want to achieve:我想要实现的数据:
[ [{'0': 2}, {'0': 1}], [{'1': 2}], [{'2': 2}, {'2': 2}] ]
As you can see internal arrays contain a dictionary with the same value of the key.如您所见,内部 arrays 包含具有相同键值的字典。
My code current code is like:我的代码当前代码如下:
dicts = [{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]
ex_list = []
sublist = []
for group in dicts:
if group.keys() in sublist:
sublist.append(group)
else:
sublist.append(group)
if group.keys() != sublist[-1]:
sublist = []
sublist.append(group)
ex_list.append(sublist)
Any help highly appreciated.任何帮助高度赞赏。
See inline comments for explanation.有关解释,请参阅内联注释。
from collections import defaultdict
dicts = [{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]
# keep track of mapping between key and values.
result = defaultdict(list)
for d in dicts:
# d.items() returns an iterable of key/value pairs.
# assuming each dictionary only has one key/value pair,
# using next(iter()), we get the first pair, and pattern-match on key and val.
key, val = next(iter(d.items())):
# with defaultdict, if key is not present in the result dictionary,
# the list will be created automatically.
result[key].append(val)
# results = {0: [2,1], 1: [2], 2: [2,2]}
# for each key, values pair in results, create a list of {key: value}
# dictionaries for each value in values.
print([[{key: value} for value in values] for key, values in result.items()])
If you want to stay close to your program, you should keep track of the current and last key I've rewritten a little bit of your code and it got the job done.如果你想靠近你的程序,你应该跟踪当前和最后一个键,我已经重写了你的代码,它完成了工作。
dicts = [{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]
ex_list = []
sublist = []
lastkey = list(dicts[0].keys())[0]
for group in dicts:
key = list(group.keys())[0]
if key == lastkey:
sublist.append(group)
else: # If key has change
ex_list.append(sublist)
sublist = []
lastkey = key
sublist.append(group)
ex_list.append(sublist) #Don't forget to include last sublist as the loop doesn't include it since no change in key
print(ex_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.