user2950162
user2950162

Reputation: 1011

Sort dictionary by specific order (list of keys)

I am trying to sort a dictionary based on the order that its keys appears in a list.

First element of the list would be the first element of the dictionary. At the end the dictionary keys wiould be in the same order as in the provided list...

I can sort by value with this code

newlist = sorted(product_list, key=lambda k: k['product']) 

but cant do it for a list

thanks for any help!

Upvotes: 4

Views: 10951

Answers (3)

John La Rooy
John La Rooy

Reputation: 304137

from collections import OrderedDict
new_dict = OrderedDict((k, old_dict[k]) for k in key_list)

Having said that, there's probably a better way to solve your problem than using an OrderedDict

If some keys are missing, you'll need to use one of

new_dict = OrderedDict((k, old_dict.get(k)) for k in key_list)

or

new_dict = OrderedDict((k, old_dict[k]) for k in key_list if k in old_dict)

depending on how you want to handle the missing keys.

Upvotes: 5

user764357
user764357

Reputation:

In Python (and most languages) dictionaries are unsorted, so you can't "sort" a dictionary.

You can retrieve and sort the keys and iterate through those:

for key in sorted(product_list.keys()):
    item = product_list[key]
    item.doSomething()

Or you can use a OrderDict, like so:

 from collections import OrderedDict

And then build the dictionary in the required order (which is up to you to determine) but below we sort using the keys:

 product_list = OrderDict(sorted(product_list.items(), key=lambda k: k[0]))

For reference, Dict.items() returns a list of tuples in the form:

[(key1, value1), (key2, value2) , ... , (keyN, valueN)]

Upvotes: 2

Matt Williamson
Matt Williamson

Reputation: 40193

By definition, a dictionary is unordered. You can use OrderedDict from collections as seen at http://docs.python.org/2/library/collections.html#collections.OrderedDict as a drop-in replacement.

Upvotes: 0

Related Questions