Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading