simplify code using an inverse dictionary in python

Viewed 72

Consider some mapping my_map that defines the order of some keys, and some dictionary my_dict that maps the same keys into some values:

my_map = {'x' : 2, 'y' : 0, 'z' : 1}
my_dict = {'x' : 'foo', 'z' : 'bar', 'y' : 'baz'}

I want to get an ordered list of the values of my_dict using the order defined by my_map. My best approach of getting there is:

inv_map = {v: k for k, v in my_map.items()}
ordered_list = [my_dict[k] for k in [inv_map[d] for d in range(len(my_map))]]

Is there a less clunky way of doing the same?

5 Answers

You could use the sorted function to order your map by value and then convert it:

[my_dict[k] for k in sorted(my_map, key=lambda key: my_map[key])]

Somewhat cleaner at least!

Let's make sure that it works:

>>> my_map = {'x' : 2, 'y' : 0, 'z' : 1}
>>> my_dict = {'x' : 'foo', 'z' : 'bar', 'y' : 'baz'}
>>> [my_dict[k] for k in sorted(my_map, key=lambda key: my_map[key])]
['baz', 'bar', 'foo']

You can actually use sorted very efficiently here using dict.get:

[my_dict[k] for k in sorted(my_map, key=my_map.get)]

In action:

>>> my_map = {'x' : 2, 'y' : 0, 'z' : 1}
>>> my_dict = {'x' : 'foo', 'z' : 'bar', 'y' : 'baz'}
>>> [my_dict[k] for k in sorted(my_map, key=my_map.get)]
['baz', 'bar', 'foo']

Depends on the situation you can init final list and pass items to the needed positions

result = [None] * len(my_dict)

for k, v in my_dict.items():
    result[my_map[k]] = v

Still another variation (I think it's different from already presented solutions):

[x[1] for x in sorted(my_dict.items(), key=lambda elem: my_map[elem[0]])]

Testing code:

my_map = {'x' : 2, 'y' : 0, 'z' : 1}
my_dict = {'x' : 'foo', 'z' : 'bar', 'y' : 'baz'}

print(my_dict.items())

sorted_result=[x[1] for x in sorted(my_dict.items(), key=lambda elem: my_map[elem[0]])]

print(sorted_result)

Or a bit differently:

sorted_result=list(zip(*sorted(my_dict.items(), key=lambda elem: my_map[elem[0]])))[1]

I wanted to use zip() to split a list of tuples into 2 lists, but in Python 3 zip() returns iterator (not a list), so (as suggested in Transpose/Unzip Function (inverse of zip)?) I wrapped it in list()

you can use sorted with the values from my_dict and a key function that sorts them with the values from my_map

ordered_list = sorted(my_dict.values(), key=lambda s:my_map[{v: k for k, v in my_dict.items()}[s]])

if it's sorted the wrong way you can use reverse=True

Related