[英]get list of dictionaries by combining values of on key based on value of another key
I have a list [{"a":11, "b":2}, {"a":12, "b":2}, {"a":13, "b":3}, {"a":14, "b":4}]
我有一个列表
[{"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
我想基于
b
值组合a
的值
I want output as [{'a':[11, 12], 'b':2}, {'a':[13], 'b':3}, {'a':[14], 'b':4}]
我想输出为
[{'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]
我已经尝试过
[{ 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': 您可以创建一个中介字典内的值映射
b
到的值的子表a
,然后用一个列表理解与键为“B”和值“一个输出中介字典的项目作为字典“:
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}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.