我有以下值重复的词典列表(coach)。

d = [
    {"players": [{"id": 179, "name": "Santosh"}], "coach": "Xavi Alonso"},
    {"players": [{"id": 180, "name": "Hari"}], "coach": "Xavi Alonso"},
    {"players": [{"id": 175, "name": "Hitman"}], "coach": "Anna Puyol"}
]

我想合并基于coach名称的重复项。我怎样才能做到这一点?
def exportplayers(request):
    d = [
        {"players": [{"id": 179, "name": "Santosh"}, {"id": 180, "name": "Hari"}], "coach": "Xavi Alonso"},
        {"players": [{"id": 175, "name": "Hitman"}], "coach": "Anna Puyol"}
    ]


    return HttpResponse(json.dumps(d))

最佳答案

您可以使用itertools模块中的groupbyitemgetter模块中的operator来完成此操作。把grouby操作看作是从记录中返回连续键和组的一种方法。为了让它工作,您需要将列表中的“项”按“coach”值排序,这就是sorted函数在这里所做的。当然,您需要提供一个键函数来定制排序顺序,一种方法是使用类似于这样的lambda表达式,但我更喜欢使用sorted(d, key=lambda _: _["coach"])的另一种方法,也就是说,您还需要为sorted(d, key=itemgetter('coach'))提供键参数,这是一个为每个元素计算键值的函数,如中所述documentation,然后再次使用groupby

from itertools import groupby
from operator import itemgetter



def exportplayers(request):
    d = [
        {"players": [{"id": 179, "name": "Santosh"}, {"id": 180, "name": "Hari"}], "coach": "Xavi Alonso"},
        {"players": [{"id": 175, "name": "Hitman"}], "coach": "Anna Puyol"}
    ]
    my_list = []
    for g, data in groupby(sorted(d, key=itemgetter('coach')),  key=itemgetter('coach')):
        my_list.append({"coach": g, "players": [player for item in data for player in item["players"]]})
    return HttpResponse(json.dumps(my_list))

使用lambda表达式作为关键函数的演示:
>>> from itertools import groupby
>>> d = [
...     {"players": [{"id": 179, "name": "Santosh"}], "coach": "Xavi Alonso"},
...     {"players": [{"id": 180, "name": "Hari"}], "coach": "Xavi Alonso"},
...     {"players": [{"id": 175, "name": "Hitman"}], "coach": "Anna Puyol"}
... ]
>>> sorted_d = sorted(d, key=lambda _: _['coach'])
>>> for g, data in groupby(sorted_d, key=lambda _: _['coach']):
...     print({"coach": g, "players": [player for item in data for player in item["players"]]})
...
{'coach': 'Anna Puyol', 'players': [{'id': 175, 'name': 'Hitman'}]}
{'coach': 'Xavi Alonso', 'players': [{'id': 179, 'name': 'Santosh'}, {'id': 180, 'name': 'Hari'}]}

关于python - 合并字典项值的重复列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36769396/

10-12 21:23