user5279
user5279

Reputation: 3

Reorder a dictionary based on a list in python

Let's say I have a python dictionary {apple: 15, orange: 22, juice: 7, blueberry:19} and I want to reorder the dictionary according to the order of this list [juice, orange, blueberry, apple]. How would I do this cleanly/efficiently? Note: the list could very well have more items than the dictionary.

Upvotes: 0

Views: 68

Answers (2)

Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

O(n) method is to simply loop over your list of ordered keys:

{k: d[k] for k in keys}

If you want to maintain the same mutable reference to the dictionary (for whatever reason), just delete the key and add it in a loop. It will naturally order itself correctly.

Upvotes: 1

Elenchus
Elenchus

Reputation: 195

As mentioned in the comments, dictionaries don't have an order in Python. Assuming you want to get the dictionary values in the same order as the list, you could do something like this. It checks to see if the key is in the dictionary first, so extra items in the list won't matter

d = {apple: 15, orange: 22, juice: 7, blueberry:19}
order = [juice, orange, blueberry, apple]
for key in order:
    if key in d:
        print(d[key])

Alternatively as @ewong mentioned, you can use an OrderedDict, which tracks the order a key is added. It seems like to re-order one you have to create a new OrderedDict, so in your case you could potentially create one from your original dictionary.

from collections import OrderedDict
ordered_d = OrderedDict([(key, d[key]) for key in order if key in d])

Upvotes: 0

Related Questions