如何对Numpy数组中的字典按伤亡总数降序排序并提取Top5城市
问题:提取印度境内伤亡总数排名前5的城市并排序
我有一个terrorismData.csv文件,需要提取印度境内伤亡总数排名前5的城市,已完成大部分代码,但卡在如何对字典按值降序排序。
原代码
city_dict = {} with open('terrorismData.csv', 'r', encoding='utf-8') as file_obj: Data = csv.DictReader(file_obj, skipinitialspace = True) for row in Data: if row['Country'] == 'India': if row['Killed'] == '': row['Killed'] = 0 if row['Wounded'] == '': row['Wounded'] = 0 total_casuality = int(float(row['Killed'])) + int(float(row['Wounded'])) if row['City'] != 'Unknown': if row['City'] in city_dict: city_dict[row['City']] += total_casuality else: city_dict[row['City']] = total_casuality np_city = np.array(city_dict) print(np_city)
当前输出(未排序)
{'New Delhi': 2095, 'Samastipur': 4, 'Bombay': 210, 'Imphal': 603, 'Aizawl': 2, 'Amapur': 2, 'Raisikah': 1, 'Champhai': 1, 'Jamshedpur': 32, 'Chennai': 366, 'Chiaplant': 1, 'Tindol': 7, 'Calcutta': 57, 'Tirupattur': 6, 'Gauhati': 112, 'Jorhat': 3, 'Massad': 1, 'Chandigarh': 333, 'Jodhpur': 2, 'Amritsar': 768, 'Tipaimukh': 6, 'Guwahati': 822, 'Harchowal': 1, 'Mothan Wala': 2, 'Qadian': 7, 'Baloda Bazar': 10 }
解决方案
你不需要将字典转成NumPy数组,直接通过Python内置的sorted()函数就能对字典按值降序排序,步骤如下:
- 对
city_dict.items()进行排序,指定排序依据为键值对的值(即伤亡总数),并设置降序; - 若只需前5个城市,对排序结果切片取前5项即可;
- Python 3.7+版本的字典本身有序,可直接将排序后的列表转为字典格式。
修正后的代码
import csv city_dict = {} with open('terrorismData.csv', 'r', encoding='utf-8') as file_obj: Data = csv.DictReader(file_obj, skipinitialspace=True) for row in Data: if row['Country'] == 'India': # 简化空值处理逻辑 killed = int(float(row['Killed'])) if row['Killed'] else 0 wounded = int(float(row['Wounded'])) if row['Wounded'] else 0 total_casuality = killed + wounded if row['City'] != 'Unknown': city_dict[row['City']] = city_dict.get(row['City'], 0) + total_casuality # 按伤亡总数降序排序 sorted_cities = sorted(city_dict.items(), key=lambda x: x[1], reverse=True) # 提取前5名城市 top5_cities = dict(sorted_cities[:5]) print(top5_cities) # 若需输出全部排序结果,执行 print(dict(sorted_cities))
输出示例(前5项)
{'New Delhi': 2095, 'Guwahati': 822, 'Amritsar': 768, 'Imphal': 603, 'Chandigarh': 333}
内容的提问来源于stack exchange,提问作者Divyansh Chaudhary
相关产品推荐
相关产品推荐

