Sherby
Sherby

Reputation: 123

Printing sorted dictionary keys along with sorted values

I am sorting a dictionary based on a particular value which is 3rd element on the list(in values) by using:

print sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]

How can I also display the keys to which those sorted values correspond to ?

Thank you for looking.

Upvotes: 2

Views: 1164

Answers (2)

falsetru
falsetru

Reputation: 369364

Use items instead of keys:

print(sorted(dict.items(), key=lambda item: item[1][2], reverse=True)[:3])

or save sorted keys, and use that to get items:

keys = sorted(dict, key=lambda key: dict[k][2], reverse=True)[:3]
items = [(key, dict[key]) for key in keys]
print(items)

if you want values seaparately:

keys = sorted(dict, key=lambda k: dict[k][2], reverse=True)[:3]
values = [dict[key] for key in keys]

BTW, don't use dict as a variable name; it shadows built-in function/type dict.

Upvotes: 2

ida
ida

Reputation: 1011

You can save the sorted list and print in format you want.

sorted_list = sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]
for key in sorted_list:
    print 'key is '+ key + ' value is '+ sorted_list[key][3] 

Upvotes: 0

Related Questions