如何合并字典列表并按城市分组,整理出场馆信息集合
字典列表按城市分组合并的实现方案
问题背景
给定如下字典列表:
data = [{'city': 'San Francisco', 'state': 'CA', 'id': 1, 'name': 'The Musical Hop'}, {'city': 'New York', 'state': 'NY', 'id': 2, 'name': 'The Dueling Pianos Bar'}, {'city': 'San Francisco', 'state': 'CA', 'id': 3, 'name': 'Park Square Live Music & Coffee'}]
需要将其按city和state分组,把同城市的场馆信息整理到venues列表中,最终得到如下结构:
[{ "city": "San Francisco", "state": "CA", "venues": [{ "id": 1, "name": "The Musical Hop" }, { "id": 3, "name": "Park Square Live Music & Coffee" }] }, { "city": "New York", "state": "NY", "venues": [{ "id": 2, "name": "The Dueling Pianos Bar" }] }]
你尝试的代码未达到预期,核心问题是:itertools.groupby仅对连续的相同键分组,且你没有构造目标结构:
import operator import itertools outputList = [] for i,g in itertools.groupby(d,key= operator.itemgetter("city")): outputList.append(list(g))
解决方案
方案一:基于itertools.groupby实现
使用groupby必须先对数据按分组键排序,同时手动构造目标结构:
import operator import itertools # 先按city排序,保证同城市的项连续(groupby的必要前提) sorted_data = sorted(data, key=operator.itemgetter("city")) output_list = [] for city, group in itertools.groupby(sorted_data, key=operator.itemgetter("city")): group_items = list(group) # 提取state(同城市的state默认一致,取第一个即可) state = group_items[0]['state'] # 构造venues列表,仅保留id和name字段 venues = [{'id': item['id'], 'name': item['name']} for item in group_items] # 拼接目标字典并加入结果列表 output_list.append({ 'city': city, 'state': state, 'venues': venues }) print(output_list)
方案二:无需依赖库的直观实现
用普通字典作为分组容器,不需要提前排序,逻辑更清晰:
grouped = {} for item in data: # 用(city, state)作为分组键,避免同一城市不同州的冲突 group_key = (item['city'], item['state']) if group_key not in grouped: grouped[group_key] = { 'city': item['city'], 'state': item['state'], 'venues': [] } # 向对应分组的venues中添加场馆信息 grouped[group_key]['venues'].append({'id': item['id'], 'name': item['name']}) # 将字典的值转为列表,得到最终结果 output_list = list(grouped.values()) print(output_list)
内容的提问来源于stack exchange,提问作者Emmanuel Folorunsho
相关产品推荐
相关产品推荐

