user3791176
user3791176

Reputation: 75

Sort a python dictionary by order of items on list

I have a dictionary like {'james': 32, 'jacob': 43, 'marie': 3}.

How do I sort the dictionary assuming I have a list like ['marie', 'jacob', 'james'], so that the new dictionary would be sorted by the order of the items in the list?

i.e, outcome:

{'marie': 3, 'jacob': 43, 'james': 32}

Upvotes: 2

Views: 64

Answers (2)

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94605

As "undefined is not a function" wrote, dictionaries are not sorted (despite what their name suggests), but collections.OrderedDict dictionaries are.

I would write the solution in an arguably clearer way (and only with basic Python), though:

>>> from collections import OrderedDict
>>> names = ['marie', 'jacob', 'james']
>>> my_dict = {'james': 32, 'jacob': 43, 'marie': 3}
>>> OrderedDict((name, my_dict[name]) for name in names)
OrderedDict([('marie', 3), ('jacob', 43), ('james', 32)])

This solution also takes less memory than the zip() approach of "undefined is not a function", since no intermediate list is constructed (in Python 2)—it may matter, in the general case—, though this could be remedied to by replacing zip() with itertools.izip(), but that would make the itemgetter() solution even heavier (with two additional imports) when Python can, like in this solution, perfectly handle the question directly and in a clear way.

As Aleksander Lidtke mentioned, maybe you don't need to create a new, sorted dictionary in the first place. Maybe looping on the names would be enough:

for name in names:
    … my_dict[name] …

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

You cannot sort a dictionary, but you can use collections.OrderedDict here:

>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> lst = ['marie', 'jacob', 'james']
>>> d = {'james': 32, 'jacob': 43, 'marie': 3}
>>> OrderedDict(zip(lst, itemgetter(*lst)(d)))
OrderedDict([('marie', 3), ('jacob', 43), ('james', 32)])

Upvotes: 3

Related Questions