简体   繁体   中英

Why won't my dictionary sorting function work properly?

I have an assignment to import a data set from a csv, and the final portion of the assignment has me stuck, specifically:

The countries are listed in order from most populous (China) to least (Holy See)

The issue comes from the fact that the resulting list orders itself alphabetically (by country) or seemingly at random.

    # 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")

I've tried changing key=lambda x: x[1] to key=lambda x: x[0] but this orders the list by country as opposed to the population count.

EDIT:

The csv for the assignment comes from here: https://think.cs.vt.edu/corgis/csv/covid/

The current output looks like this but needs to look like this

Further, I cannot use pd for this assignment.

Assuming you have a dictionary where the key is the country name and the value is it's population, to print out an ordered list by decreasing population you can do the following:

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]}')

This produces the following output:

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

Turns out the solution here is very simple. The population data needs to be changed from a str to an int.

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

This allows for the population to properly be sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM