简体   繁体   中英

Sort Python dictionary by it's keys using another Python list

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!

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}

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)])

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 (eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM