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!
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.
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 .
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.
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']))
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With