python:按多个字典键分组

2024-04-19 05:41:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按年份和城市分组,同时在输出上累积日期和pts,我是python新手,不知道如何进行,你有什么想法吗? 我提取了列表年份和列表城市,不确定这是否有用? 多谢各位

list_pts = [
    {'city' : 'Madrid', 'year' : '2017', 'date' : '05/07/2017', 'pts' : 7},
    {'city' : 'Madrid', 'year' : '2017', 'date' : '14/11/2017', 'pts' : 5},
    {'city' : 'Londres', 'year' : '2018', 'date' : '25/02/2018', 'pts' : 5},
    {'city' : 'Paris', 'year' : '2019', 'date' : '17/04/2019', 'pts' : 4},
    {'city' : 'Londres', 'year' : '2019', 'date' : '15/06/2019', 'pts' : 8},    
    {'city' : 'Paris', 'year' : '2019', 'date' : '21/08/2019', 'pts' : 8},
    {'city' : 'Londres', 'year' : '2019', 'date' : '04/12/2019', 'pts' : 2}]

list_year = ['2017', '2018', '2019']
list_city = ['Paris', 'Madrid', 'Londres']

output =
    [{'year' : '2017', 'city' : 'Madrid', 'date' : ['05/07/2017', '14/11/2017'], 'pts' :[5, 7]},
    {'year' : '2018', 'city' : 'Londres', 'date' : ['25/02/2018'], 'pts' :[5]},
    {'year' : '2019', 'city' : 'Londres', 'date' : ['15/06/2019', '04/12/2019'], 'pts' :[8, 2]},
    {'year' : '2019', 'city' : 'Paris', 'date' : ['17/04/2019', '21/08/2019'], 'pts' :[4, 8]}]

Tags: city列表outputdateyearptslist年份
3条回答

一种基于使用^{}对值进行分组的方法是执行以下操作:

from collections import defaultdict
from operator import itemgetter
import pprint

list_pts = [
    {'city': 'Madrid', 'year': '2017', 'date': '05/07/2017', 'pts': 7},
    {'city': 'Madrid', 'year': '2017', 'date': '14/11/2017', 'pts': 5},
    {'city': 'Londres', 'year': '2018', 'date': '25/02/2018', 'pts': 5},
    {'city': 'Paris', 'year': '2019', 'date': '17/04/2019', 'pts': 4},
    {'city': 'Londres', 'year': '2019', 'date': '15/06/2019', 'pts': 8},
    {'city': 'Paris', 'year': '2019', 'date': '21/08/2019', 'pts': 8},
    {'city': 'Londres', 'year': '2019', 'date': '04/12/2019', 'pts': 2}]

# function for extracting city and year (to be used as a grouping key)
city_and_year = itemgetter("city", "year")

# function for extracting dates and points 
date_and_points = itemgetter("date", "pts")

# group by key (city, year) by using a defaultdict
res = defaultdict(list)
for record in list_pts:
    res[city_and_year(record)].append(date_and_points(record))

# transform to the desired format
result = []
for (city, year), values in res.items():
    dates, points = zip(*values)
    result.append({"city": city, "year": year, "dates": list(dates), "pts": list(points)})

# use pprint to nicely print the output
pprint.pprint(result)

输出

[{'city': 'Madrid',
  'dates': ['05/07/2017', '14/11/2017'],
  'pts': [7, 5],
  'year': '2017'},
 {'city': 'Londres', 'dates': ['25/02/2018'], 'pts': [5], 'year': '2018'},
 {'city': 'Paris',
  'dates': ['17/04/2019', '21/08/2019'],
  'pts': [4, 8],
  'year': '2019'},
 {'city': 'Londres',
  'dates': ['15/06/2019', '04/12/2019'],
  'pts': [8, 2],
  'year': '2019'}]

您可以使用^{}将dict与^{}组合起来进行分组:

from itertools import groupby
from operator import itemgetter

list_pts = [
    {'city': 'Madrid', 'year': '2017', 'date': '05/07/2017', 'pts': 7},
    {'city': 'Madrid', 'year': '2017', 'date': '14/11/2017', 'pts': 5},
    {'city': 'Londres', 'year': '2018', 'date': '25/02/2018', 'pts': 5},
    {'city': 'Paris', 'year': '2019', 'date': '17/04/2019', 'pts' : 4},
    {'city': 'Londres', 'year': '2019', 'date': '15/06/2019', 'pts': 8},
    {'city': 'Paris', 'year': '2019', 'date': '21/08/2019', 'pts': 8},
    {'city': 'Londres', 'year': '2019', 'date': '04/12/2019', 'pts': 2}
]

city_year_getter = itemgetter('city', 'year')
date_pts_getter = itemgetter('date', 'pts')

result = []
for (city, year), objs in groupby(sorted(list_pts, key=city_year_getter), 
                                  city_year_getter):
    dates, ptss = zip(*map(date_pts_getter, objs))
    result.append({
        'city': city,
        'year': year,
        'date': list(dates),
        'pts': list(ptss)
    })
list_pts = [
  {'city': 'Madrid',  'year': '2017', 'date': '05/07/2017', 'pts': 7},
  {'city': 'Madrid',  'year': '2017', 'date': '14/11/2017', 'pts': 5},
  {'city': 'Londres', 'year': '2018', 'date': '25/02/2018', 'pts': 5},
  {'city': 'Paris',   'year': '2019', 'date': '17/04/2019', 'pts': 4},
  {'city': 'Londres', 'year': '2019', 'date': '15/06/2019', 'pts': 8},
  {'city': 'Paris',   'year': '2019', 'date': '21/08/2019', 'pts': 8},
  {'city': 'Londres', 'year': '2019', 'date': '04/12/2019', 'pts': 2}]

group_by = {}
for pt in list_pts:
  d = group_by.setdefault((pt['year'], pt['city']), {})
  for k, v in pt.items():
    if k not in {'year', 'city'}:
      d.setdefault(k, []).append(v)

output = []
for (year, city), rest in group_by.items():
  output.append({'year': year, 'city': city} | rest)

对于3.9之前的Python,请参见this answer关于字典合并

这是一个使用(year, city)对作为键(可以通过Python中的元组完成)并将所有其他项收集到列表中的问题。从group_byoutput的转换只是一个装饰性的东西

相关问题 更多 >