Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sorting multidimensional dict by a specific column

I know there are tons of questions about this but I'm trying to sort the dict below by the hitrate column.

data = {
    'a': {'get': 1, 'hitrate': 1, 'set': 1},
    'b': {'get': 4, 'hitrate': 20, 'set': 5},
    'c': {'get': 3, 'hitrate': 4, 'set': 3}
}

I tried a bunch of things, the most promising being the method below which seems to error out.

s = sorted(data, key=lambda x: int(x['hitrate']))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: string indices must be integers, not str

Can I get some help with this please?

Thanks!

like image 550
Alex Dicianu Avatar asked Apr 25 '17 18:04

Alex Dicianu


People also ask

How do you sort a 2D dictionary in Python?

Method #1 : Using OrderedDict() + sorted() This task can be performed using OrderedDict function which converts the dictionary to specific order as mentioned in its arguments manipulated by sorted function in it to sort by the value of key passed.

How do you sort a column by a list in Python?

Use sorted() with a lambda function to sort a multidimensional list by column. Call sorted(iterable, key=None) with key set to a lambda function of syntax lambda x: x[i] to sort a multidimensional list iterable by the i th element in each inner list x .

Can you sort an ordered dict?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.


2 Answers

Iterating a dict yields the keys, so you need to lookup x in the dict again:

sorted(data, key=lambda x: int(data[x]['hitrate']))

If you want the values too, then sort the items:

sorted(data.items(), key=lambda item: int(item[1]['hitrate']))
like image 183
wim Avatar answered Oct 04 '22 20:10

wim


Using a dict as an iterable will only cause the keys to be iterated and not the values, so x in your lambda will only be "a", "b", and "c" You're basically doing "a"["hitrate"], which causes a TypeError. Try using x as keys into your dictionary.

>>> data = {
...     'a': {'get': 1, 'hitrate': 1, 'set': 1},
...     'b': {'get': 4, 'hitrate': 20, 'set': 5},
...     'c': {'get': 3, 'hitrate': 4, 'set': 3}
... }
>>> s = sorted(data, key=lambda x: int(data[x]['hitrate']))
>>> s
['a', 'c', 'b']
like image 38
Kevin Avatar answered Oct 04 '22 20:10

Kevin