0

I have a list of words:

['apple', 'zoo', 'chicken', 'needle', 'car', 'computer']

I also have a dictionary with keys and values:

{'zoo': 42, 'needle': 32, 'computer': 18, 'apple': 39, 'car': 11, 'chicken': 12}

The keys of my dictionary are all from the list of words. How can I sort the dictionary so that the order of its keys is the same as the order of the words in the list? So once sorted, my dictionary should look like this:

{'apple': 39, 'zoo': 42, 'chicken': 12, 'needle': 32, 'car': 11, 'computer': 18}

Thanks so much!

4
  • 1
    Dictionaries don't preserve order. An available ordered version of a dictionary is collections.OrderedDict Commented Jul 16, 2017 at 18:07
  • First of all you should be aware that dictionaries are unordered in Python 3.5 and below. For ordered dictionaries you can use collections.OrderedDict. Commented Jul 16, 2017 at 18:08
  • @jmd_dk pardon me for hijacking the comment's section for this question, but are dictionaries really ordered in Python 3.6? Looks like I missed that part of the docs then. Nvm found the docs! :) Commented Jul 16, 2017 at 18:11
  • @ViníciusAguiar They are indeed. I recommend this nice talk for an overview of the recent (and historic) changes to dicts: youtube.com/watch?v=npw4s1QTmPg Commented Jul 16, 2017 at 18:18

3 Answers 3

3

For python versions < 3.6, dictionaries do not maintain order, and sorting a dictionary is consequently not possible.

You may use the collections.OrderedDict to build a new dictionary with the order you want:

In [269]: from collections import OrderedDict

In [270]: keys = ['apple', 'zoo', 'chicken', 'needle', 'car', 'computer']
     ...: dict_1 = {'zoo': 42, 'needle': 32, 'computer': 18, 'apple': 39, 'car': 11, 'chicken': 12}
     ...: 

In [271]: dict_2 = OrderedDict()

In [272]: for k in keys:
     ...:     dict_2[k] = dict_1[k]
     ...:     

In [273]: dict_2
Out[273]: 
OrderedDict([('apple', 39),
             ('zoo', 42),
             ('chicken', 12),
             ('needle', 32),
             ('car', 11),
             ('computer', 18)])

In Python3.6, a simple dict comprehension suffices:

>>> {x : dict_1[x] for x in keys}
{'apple': 39, 'zoo': 42, 'chicken': 12, 'needle': 32, 'car': 11, 'computer': 18}
Sign up to request clarification or add additional context in comments.

2 Comments

Great, that works! (I'm using 3.6) What if my list has values that my dictionary doesn't? How do I bypass the KeyError without stopping the loop?
@QuantumJuker You'll need to add an if condition: if k in dict_1: dict_2[k] = dict_1[k]
0

You can used OrderedDict since regular dictionaries are unordered. For your case you could do this:

from collections import OrderedDict
od = OrderedDict()

ll = ['apple', 'zoo', 'chicken', 'needle', 'car', 'computer']
d = {'zoo': 42, 'needle': 32, 'computer': 18, 'apple': 39, 'car': 11, 'chicken': 12} 

for f in ll:
  od[f] = d[f]
#Outputs: OrderedDict([('apple', 39), ('zoo', 42), ('chicken', 12), ('needle', 32), ('car', 11), ('computer', 18)])

Comments

-1

Python dict doesn't preserve order by default, you should use collections.OrderedDict. The first item you put into OrderedDict is the first item you will get when you enumerate it (e.g. using for).

from collections import OrderedDict

order_list = ['apple', 'zoo', 'chicken', 'needle', 'car', 'computer']
unordered_dict = {'zoo': 42, 'needle': 32, 'computer': 18, 'apple': 39, 'car': 11, 'chicken': 12}
ordered_dict = OrderedDict()
for item in order_list:
    ordered_dict[item] = unordered_dict[item]

for k, v in unordered_dict.items():
    print(k, v)

for k, v in ordered_dict.items():
    print(k, v)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.