假设我们有一个包含多个JSON对象的列表,每个JSON对象都有一个属性“color”,我们想按颜色分组排序。
做法如下:
import json
# 读取JSON列表
with open('data.json') as f:
data = json.load(f)
groups = {}
for item in data:
color = item['color']
if color in groups:
groups[color].append(item)
else:
groups[color] = [item]
for color, items in groups.items():
sorted_items = sorted(items, key=lambda x: x['price'])
groups[color] = sorted_items
for color, items in groups.items():
print(f'Color: {color}')
for item in items:
print(f'\tPrice: {item["price"]}, Brand: {item["brand"]}')
完整代码示例:
import json
# 读取JSON列表
with open('data.json') as f:
data = json.load(f)
# 定义一个字典来保存分组数据
groups = {}
# 遍历JSON列表,将颜色相同的对象添加到同一个组中
for item in data:
color = item['color']
if color in groups:
groups[color].append(item)
else:
groups[color] = [item]
# 排序
for color, items in groups.items():
sorted_items = sorted(items, key=lambda x: x['price'])
groups[color] = sorted_items
# 输出结果
for color, items in groups.items():
print(f'Color: {color}')
for item in items:
print(f'\tPrice: {item["price"]}, Brand: {item["brand"]}')
注意:本示例假设包含在JSON对象中
上一篇:按属性值将对象分组成数组
下一篇:按属性值排序字典