Deepak B
Deepak B

Reputation: 2335

Python Converting a sorted dictionary to list?

I have two lists

L1 = ['tom', 'jerry', 'spike', 'fido', 'donald', 'mickey']
L2 = [3,5,7,6,9,3]
dictionary = dict(zip(L1, L2))
print dictionary

sorted_friends = sorted(dictionary.iteritems(), key = operator.itemgetter(1), reverse= True)
print sorted_friends

Basically, I am creating a dictionary from L1 and L2. {'mickey': 3, 'tom': 3, 'jerry': 5, 'donald': 9, 'fido': 6, 'spike': 7} Sorting (reverse) sorting it by value, which gives me:[('donald', 9), ('spike', 7), ('fido', 6), ('jerry', 5), ('mickey', 3), ('tom', 3)]

I want a list of the top 3 keys: like [donald,spike,fido] But the problem is if I use any method that I know like casting to dict() etc its spoiling the sorting.

Upvotes: 1

Views: 394

Answers (2)

John La Rooy
John La Rooy

Reputation: 304147

If you just want the 3 largest, why not just use heapq?

>>> L1 = ['tom', 'jerry', 'spike', 'fido', 'donald', 'mickey']
>>> L2 = [3,5,7,6,9,3]
>>> dictionary = dict(zip(L1, L2))
>>> import heapq
>>> heapq.nlargest(3, dictionary, key=dictionary.get)
['donald', 'spike', 'fido']

It's also possible, but a little tricky to skip creating the dictionary

>>> heapq.nlargest(3, L1, key=lambda x, i2=iter(L2): next(i2))
['donald', 'spike', 'fido']

Upvotes: 1

Amber
Amber

Reputation: 526583

No need to use a dict; just create the list of tuples and sort them by the appropriate field.

sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)[:3]

You can of course use operator.itemgetter(1) instead of the lambda, as you please.

If you just want the names after the fact, you can modify this:

[a for a,_ in sorted(zip(L1, L2), key=lambda x: x[1], reverse=True)][:3]

Note that you could also conveniently avoid having to specify a custom sort function at all by simply reversing the order:

[b for _,b in sorted(zip(L2, L1), reverse=True)][:3]

This works because the default sort order for tuples sorts them according to their first element, then their second, and so on - so it will sort by the values first.

Upvotes: 5

Related Questions