0

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.

user5279
  • 3
  • 4
  • Dictionaries aren't ordered in python - do you want to pull out the values in a specific order? – Elenchus Jul 28 '20 at 01:33
  • Why would you want to reorder a dictionary? Dictionaries are unordered, so it doesn't matter what order it's in – F.M Jul 28 '20 at 01:34
  • 2
    @F.M Dictionaries have guaranteed stable iterable order since Python 3.6. – Mateen Ulhaq Jul 28 '20 at 01:57
  • @MateenUlhaq: Technically, it's only a language guarantee as of 3.7, but yes, CPython and PyPy (the only two implementations of Python that have reached 3.6 to my knowledge) both include insertion-ordered `dict`s as an implementation detail. – ShadowRanger Jul 28 '20 at 02:40

2 Answers2

1

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.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • There's no guarantee the order will be maintained in this method. You would have to sort the dictionary each time the order mattered. See https://stackoverflow.com/questions/20192950/why-items-order-in-a-dictionary-changed-in-python – Elenchus Jul 28 '20 at 02:09
  • 2
    Python 3.6+ dictionaries are all insertion-ordered. – Mateen Ulhaq Jul 28 '20 at 02:12
0

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])
Elenchus
  • 195
  • 2
  • 10