Reputation: 1698
I know that dictionaries aren't sortable, that being said, I want the representation of the dictionary that is sorted upon that value which is a list. Example:
some_dict= {
"a": [0, 0, 0, 0, 0],
"b": [1400, 50, 30, 18, 0],
"c": [800, 30, 14, 14, 0],
"d": [5000, 100, 30, 50, .1],
"for fun": [140000, 1400, 140, 140, .42]
}
I want to sort by the first item in the list of each.
I tried something like:
sorted(some_dict.items(), key = lambda for x in some_dict: some_dict[x][0])
but I get invalid syntax.
Thanks in advance.
Upvotes: 1
Views: 72
Reputation: 59974
You're on the right track, but you can't put a for-loop in a lambda (hence the error):
>>> sorted(some_dict.items(), key=lambda x: x[1][0])
[('a', [0, 0, 0, 0, 0]), ('c', [800, 30, 14, 14, 0]), ('b', [1400, 50, 30, 18, 0]), ('d', [5000, 100, 30, 50, 0.1]), ('for fun', [140000, 1400, 140, 140, 0.42])]
If you want to keep this order in a dictionary, you can use collections.OrderedDict
:
>>> from collections import OrderedDict
>>> mydict = OrderedDict(sorted(some_dict.items(), key=lambda x: x[1][0]))
>>> print(mydict)
OrderedDict([('a', [0, 0, 0, 0, 0]), ('c', [800, 30, 14, 14, 0]), ('b', [1400, 50, 30, 18, 0]), ('d', [5000, 100, 30, 50, 0.1]), ('for fun', [140000, 1400, 140, 140, 0.42])])
>>> print(mydict['a'])
[0, 0, 0, 0, 0]
Upvotes: 4
Reputation: 298166
lambda
s are anonymous functions, but they can only execute expressions in Python:
lambda pair: pair[1][0]
You could also write it verbosely:
def sorting_func(pair):
key, value = pair
return value[0]
sorted(some_dict.items(), key=sorting_func)
Upvotes: 1