简体   繁体   中英

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?

ie, outcome:

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

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)])

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] …

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