[英]Create a sublist from list of dictionaries
我想根據字典鍵從當前字典列表創建一個子列表。
我的數據:
[{'0': 2}, {'0': 1}, {'1': 2}, {'2': 2}, {'2': 2}]
我想要實現的數據:
[ [{'0': 2}, {'0': 1}], [{'1': 2}], [{'2': 2}, {'2': 2}] ]
如您所見,內部 arrays 包含具有相同鍵值的字典。
我的代碼當前代碼如下:
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)
任何幫助高度贊賞。
有關解釋,請參閱內聯注釋。
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()])
如果你想靠近你的程序,你應該跟蹤當前和最后一個鍵,我已經重寫了你的代碼,它完成了工作。
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.