我想根据字典键从当前字典列表中创建一个子列表。
我的数据:
[{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]
我想要实现的数据:
[ [{'0': 2}, {'0': 1}], [{'1': 2}], [{'2': 2}, {'2': 2}] ]
如您所见,内部数组包含一个具有相同键值的字典。
我的代码当前代码是这样的:
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)
非常感谢任何帮助。
答案 0 :(得分:0)
请参阅内嵌注释以获取解释。
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()])
答案 1 :(得分:0)
如果你想接近你的程序,你应该跟踪当前和最后一个键,我已经重写了你的一些代码,它完成了工作。
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)