Home > Blockchain >  Python: How can I fully print out the first n keys and values of the dictionary
Python: How can I fully print out the first n keys and values of the dictionary

Time:05-04

I want to print the keys and values with the values sorted from the largest to the smallest

costumer_dict = {3:30, 1:22, 2:22}
sorted_values = [30, 22, 22]
sorted_dict = {}

for i in sorted_values:
        for k in customer_dict.keys():
            if customer_dict[k] == i:
                sorted_dict[k] = customer_dict[k]
                break

for x in list(sorted_dict)[:3]:
    print(str(x)   ','   str(sorted_dict[x]))

The answer I was expected is

3,30
1,22
2,22

But it will only print out

3,30
1,22

But if there are no duplicate values in the dictionary, it will print out the correct answer, so I'm wondering why this will happen. I'm a beginner of python, can someone tell me where the code is wrong?

CodePudding user response:

Your for loop stops at the first matched value. It does not find all of the matches for your value.

There's no need to create a separate dictionary. You can sort the items of the dictionary based on value in descending order, and then iterate over the result of that sorting process.

costumer_dict = {3:30, 1:22, 2:22}

for key, value in sorted(costumer_dict.items(), key=lambda x: x[1], reverse=True):
    print(f"{key},{value}")

This outputs:

3,30
1,22
2,22

CodePudding user response:

You needed to remove the break. This code produces your desired example.

customer_dict = {3:30, 1:22, 2:22}
sorted_values = [30, 22, 22]
sorted_dict = {}

for i in sorted_values:
        for k in customer_dict.keys():
            if customer_dict[k] == i:
                sorted_dict[k] = customer_dict[k]
            


for x in list(sorted_dict)[:3]:
    print(str(x)   ','   str(sorted_dict[x]))
  • Related