user9451912
user9451912

Reputation:

Sort dictionary by another list or dictionary

I need sort my dictionary by another element who determine your order.

unsorted_dict = {'potato':'whatever1', 'tomato':'whatever2', 'sandwich':'whatever3'}

This sorting can come as a list or a dictionary, whichever is easier.

ordination = ['sandwich', 'potato', 'tomato']

Dictionary after sort:

sorted_dict = {'sandwich':'whatever3', 'potato':'whatever1', 'tomato':'whatever2'}

Upvotes: 11

Views: 4961

Answers (2)

imreal
imreal

Reputation: 10358

You can use an OrderedDict like this:

from collections import OrderedDict

sorted_dict = OrderedDict([(el, unsorted_dict[el]) for el in ordination])

What it does is create a list of tuples (pairs) using the ordination as first element and the value in unsorted_dict as second, then the OrderedDict uses this list to create a dictionary ordered by insertion.

It has the same interface as a dict and introduces no external dependencies.

EDIT: In python 3.6+ an ordinary dict will preserve insertion ordering as well.

Upvotes: 10

WholesomeGhost
WholesomeGhost

Reputation: 1121

I think this is the easiest way to do it:

sorted_dict = dict()
sorted_list = list((i, unsorted_dict.get(i)) for i in ordination)
for i in sorted_list:
    sorted_dict.setdefault(i[0], i[1])

The results is:

{'sandwich': 'whatever3', 'potato': 'whatever1', 'tomato': 'whatever2'}

This, like the second answer, first createas a tuple of sorted pairs but doesn't rely on any outside libraries.

Upvotes: 0

Related Questions