简体   繁体   中英

How to sort a dictionary based on values with tuple

Here I have dictionary like

d_ = {"k3":(2,3), "k1":(4,5), "k5":(8,9), "k2":(6,8), "k4":(2,7)}

I have to sort this based on descending order of first value in the tuples. I am doing this:

 sorted(d_.items(), key=d_.get(1) , reverse=True)

But I am getting this:

[('k5', (8, 9)), ('k4', (2, 7)), ('k3', (2, 3)), ('k2', (6, 8)), ('k1', (4, 5))]

The Output should look like this:

[("k5",(8,9)),("k2",(6,8)),("k1",(4,5)),("k3",(2,3)),("k4",(2,7))] 

You can try:

>>> [(k, d_.get(k)) for k in sorted(d_, key=d_.get, reverse=True)]
[('k5', (8, 9)), ('k2', (6, 8)), ('k1', (4, 5)), ('k4', (2, 7)), ('k3', (2, 3))]

NOTE : The last two elements for this answer are swapped from the example answer the OP gave.

Something as simple as this could also work:

>>> d_ = {"k3":(2,3), "k1":(4,5), "k5":(8,9), "k2":(6,8), "k4":(2,7)}
>>> sorted(d_.items(), key = lambda x : -x[1][0])
[('k5', (8, 9)), ('k2', (6, 8)), ('k1', (4, 5)), ('k3', (2, 3)), ('k4', (2, 7))]

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