I have a list [{"a":11, "b":2}, {"a":12, "b":2}, {"a":13, "b":3}, {"a":14, "b":4}]
I want to combine values of a
based on values of b
I want output as [{'a':[11, 12], 'b':2}, {'a':[13], 'b':3}, {'a':[14], 'b':4}]
I have tried [{ k:list(set([d[k] for d in a])) for k in a[0] } for i in a]
You can create an intermediary dict to map values of b
to a sub-list of the values of a
, and then use a list comprehension that outputs the items of the intermediary dict as a dict with keys as 'b' and values as 'a':
mapping = {}
for d in lst:
mapping.setdefault(d['b'], []).append(d['a'])
[{'a': v, 'b': k} for k, v in mapping.items()]
This returns:
[{'a': [11, 12], 'b': 2}, {'a': [13], 'b': 3}, {'a': [14], 'b': 4}]
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.