Home > database >  Pythonic/List comprehension way of creating a list from a dict where the values are guaranteed to be
Pythonic/List comprehension way of creating a list from a dict where the values are guaranteed to be

Time:10-27

Suppose I have a python dict like:

my_dict = {"foo": 1, "bar": 0, "more": 2}

I want to create an ordered list of the keys such that the order follows the value increasingly. The values are guaranteed to be unique and in the range of 0.. len(my_dict) -1. The following code achieves the objective:

    my_list = []
    for i in range(0, len(self.my_dict)):
        for key, idx in self.my_dict.items():
            if idx == i:
                my_list.append(key)
    my_list.reverse()

Is there a more pythonic/list comprehension way of achieving the same objective?

CodePudding user response:

Just plain old sort with a key:

>>> my_dict = {"foo": 1, "bar": 0, "more": 2}
>>> sorted(my_dict, key=my_dict.get)
['bar', 'foo', 'more']

Include reverse keyword if you want values decreasing (your question says increasing but your example code does decreasing, so I'm not sure)

>>> sorted(my_dict, key=my_dict.get, reverse=True)
['more', 'foo', 'bar']

The values are guaranteed to be unique and in the range of 0.. len(my_dict) -1.

In this special case you also have some O(n) solutions available. Sorting would be O(n log n).

>>> my_dict_inverse = {v: k for k, v in my_dict.items()}
>>> [my_dict_inverse[i] for i in range(len(my_dict))]
['bar', 'foo', 'more']

Or:

L = [None] * len(my_dict)
for val, i in my_dict.items():
    L[i] = val

I would still take the sorted approach unless the data is very big, though.

CodePudding user response:

you can use sort with key parameter:

my_dict = {"foo": 1, "bar": 0, "more": 2}

output = [k for k, _ in sorted(my_dict.items(), key=lambda x: x[1])]
print(output) # ['bar', 'foo', 'more']
  • Related