首页 > 解决方案 > 为什么我的字典排序功能不能正常工作?

问题描述

我有一个从 csv 导入数据集的任务,任务的最后一部分让我卡住了,特别是:

这些国家按人口最多(中国)到最少(罗马教廷)的顺序列出

问题来自于结果列表按字母顺序(按国家/地区)或看似随机的事实。

    # Create dictionary of data
    data = {}
    for i in range(len(countries)):
        data[countries[i]] = population[i]

    # Sort the dictionary by population size
    sorted_data = sorted(data.items(), key=lambda x: x[1], reverse=True)

    # Save and print the formated data
    for i in range(len(sorted_data)):
        outfile.write("{} ".format(i+1) + f'{sorted_data[i][0]:{50}} {sorted_data[i][1]:{50}}' + "\n")
        print("{} ".format(i+1) + f'{sorted_data[i][0]:{50}} {sorted_data[i][1]:{50}}' + "\n")

我已经尝试更改key=lambda x: x[1]为,key=lambda x: x[0]但这会按国家/地区而不是人口计数来排序。

编辑:

作业的 csv 来自这里: https ://think.cs.vt.edu/corgis/csv/covid/

当前输出看起来像这样,但需要看起来像这样

此外,我不能将 pd 用于此作业。

标签: pythoncsvsorting

解决方案


假设您有一个字典,其中键是国家名称,值是人口,要通过减少人口打印出有序列表,您可以执行以下操作:

cd = {'A':12, 'B': 8, 'C':45, 'D': 4}  # Sample Dictionary
sd = sorted(cd, key= lambda x: cd[x], reverse=True) # Sorted List of Keys
for k in sd:
    print(f'Country: {k} has population {cd[k]}')

这会产生以下输出:

Country: C has population 45
Country: A has population 12
Country: B has population 8
Country: D has population 4

​</p>


推荐阅读