Python:如何合并1个n dicts列表

时间:2017-11-09 18:07:32

标签: python dictionary

我有这个清单:

我希望能够根据部门对这些词典进行分组

departments = [
{
    "department": 4,
    "user": 1,
    "status": False
},
{
    "department": 2,
    "user": 1,
    "status": True
},
{
    "department": 2,
    "user": 2,
    "status": True
}]

我想要这个:

departments = [
{
    "department": 4,
    "user": 1,
    "status": False
},
{
    "department": 2,
    "user": [1, 2]
    "status": True
}]

怎么做?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

import collections
new_data = [(a, list(b)) for a, b in itertools.groupby(departments, key=lambda x:x["department"])]
final_data = [{"department":a, 'status':list(set([i["status"] for i in b])), 'user':[i["user"] for i in b]} for a, b in new_data]

输出:

[{'department': 4, 'status': [False], 'user': [1]}, {'department': 2, 'status': [True], 'user': [1, 2]}]

该解决方案考虑了每个键的值具有多种可能性的可能性。因此,“status”和“user”的每个值都在一个列表中。

或者,要完美匹配OP的期望输出:

final_data = [{"department":a, 'status':list(set([i["status"] for i in b]))[0] if len(set([i["status"] for i in b])) == 1 else list(set([i["status"] for i in b])), 'user':list(set([i["user"] for i in b]))[0] if len(set([i["user"] for i in b])) == 1 else list(set([i["user"] for i in b]))} for a, b in new_data]

输出:

[{'department': 4, 'status': False, 'user': 1}, {'department': 2, 'status': True, 'user': [1, 2]}]