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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.