How to sort list-based dictionary in python

I have a dictionary

a = {'ground': obj1, 'floor 1': obj2, 'basement': obj3} 

I have a list.

 a_list = ['floor 1', 'ground', 'basement'] 

I want to sort a dictionary using its list-based keys. Is it possible to do this?

i.e:.

 sort(a).based_on(a_list) #this is wrong. But I want something like this. 
+7
python sorting dictionary list
source share
2 answers

Naive way, sorting a list (key, value):

 sorted(a.items(), key=lambda pair: a_list.index(pair[0])) 

Fast track by first creating an index map:

 index_map = {v: i for i, v in enumerate(a_list)} sorted(a.items(), key=lambda pair: index_map[pair[0]]) 

Both assume that a_list contains all the keys found in a .

Demo:

 >>> a = {'ground': 'obj1', 'floor 1': 'obj2', 'basement': 'obj3'} >>> a_list = ('floor 1', 'ground', 'basement') >>> sorted(a.items(), key=lambda pair: a_list.index(pair[0])) [('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')] >>> index_map = {v: i for i, v in enumerate(a_list)} >>> sorted(a.items(), key=lambda pair: index_map[pair[0]]) [('floor 1', 'obj2'), ('ground', 'obj1'), ('basement', 'obj3')] 
+8
source share

You can simply get the values โ€‹โ€‹in the order of the keys provided in the list and make a new list of key-value pairs.

Example:

 d = a # dictionary containing key-value pairs that are to be ordered l = a_list # list of keys that represent the order for the dictionary # retrieve the values in order and build a list of ordered key-value pairs ordered_dict_items = [(k,d[k]) for k in l] 
+7
source share

All Articles