user6168548
user6168548

Reputation:

Python - Print items from a dict sorted by value

Here is a dict of pets and how many of them.

{"Birds" : 2, "Cats" : 3, "Dogs" : 4}

I want to print the items sorted by largest number of the same pet to the smallest number of the same pet, or vice versa.

Desired output:

('Dogs', 4)
('Cats', 3)
('Birds', 2)

And

('Birds', 2)
('Cats', 3)
('Dogs', 4)

How could this be done?

I do not want to import anything.

Upvotes: 0

Views: 3317

Answers (3)

AJP
AJP

Reputation: 47

For purposes of understanding from a beginners point of view sometimes it is better to write more code to achieve this. As dictionaries cannot be sorted, you can take each key and value pair and return a list with a simple function.

mydict = {"Birds" : 2, "Cats" : 3, "Dogs" : 4}
def sortDict(dictionary):
    sorted_values = sorted(dictionary.values())
    sorted_keys = sorted(dictionary.keys())
    #sorted_values.reverse()
    #sorted_keys.reverse()
    for key, value in zip(sorted_keys, sorted_values):
        print(key, value)
sortDict(mydict)

Simply remove the # characters to reverse the result.

Upvotes: 0

nicky_s
nicky_s

Reputation: 39

with lambda expression x[1] stands for values, x[0] for keys in key-value pair from a dictionary.

sorted(d.items(), key=lambda x: x[1], reverse=True) 
sorted(d.items(), key=lambda x: x[0])

without lambda expr, operator.itemgetter does the same thing:

from operator import itemgetter

sorted(d.items(), key=itemgetter(1), reverse=True)
sorted(d.items(), key=itemgetter(0))

Upvotes: 1

Reut Sharabani
Reut Sharabani

Reputation: 31339

Using the built-in sorted function with a special ranking function and a reverse=True argument:

for item in sorted(dict.items(), key=lambda x: x[1], reverse=True):
    print(item)

A key of lambda x: -x[1] should also work (without reverse argument).

Upvotes: 0

Related Questions