如何仅按整数字段对包含字符串与整数的字典列表进行排序
Python字典列表按指定整数字段排序实现方案
错误代码原因
你当前的代码是对单个字典的键值对做排序,完全不符合需求:
- 首先你的原始数据结构错误,你给出的示例是一个包含重复key的非法字典,实际应该是「多个独立字典组成的列表」,重复key在单个字典里会被直接覆盖,无法保留多条数据。
- 你写的
sorted(dict.items(), key=lambda item: int(item[0]))逻辑是尝试把字典的key转成整数排序,和按Age字段排序的需求完全不匹配。
正确实现步骤
1. 修正原始数据结构为字典列表
# 每条数据为独立字典,存放在同一个列表中 data_list = [ {"Name": "Mark","country": "England", "Age":15}, {"Name": "Tom","country": "Poland", "Age":10}, {"Name": "Sam","country": "USA", "Age":19}, {"Name": "Bob","country": "Italy", "Age":17} ]
2. 按Age字段升序排序
直接对列表调用sorted()方法,排序key指定为每个字典的Age字段即可:
# 升序排序,如需降序可添加参数 reverse=True sorted_list = sorted(data_list, key=lambda item: item["Age"])
3. 遍历输出结果(可选)
for item in sorted_list: print(item)
输出结果
{'Name': 'Tom', 'country': 'Poland', 'Age': 10} {'Name': 'Mark', 'country': 'England', 'Age': 15} {'Name': 'Bob', 'country': 'Italy', 'Age': 17} {'Name': 'Sam', 'country': 'USA', 'Age': 19}
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

