Sorting a dictionary which has values as list, and sorting based on the elements inside this list
I have a list
A={'k3': ['b', 3],'开发者_如何学运维k2': ['a', 1],'k1': ['a', 3],'k4': ['c', 2],'k5': ['b', 2]}
I want to sort the above dictionary first by letters 'a','b' and 'c' in an ascending order
and then based on values 3,2,1 in the descending order. So my output should look something like
A={'k1': ['a', 3],'k2': ['a', 1],'k3': ['b', 3],'k5': ['b', 2],'k4': ['c', 2]}
How do I do it?
Dictionaries are unordered, so you can't create a sorted dictionary.
If you just want a list of dictionary keys, sorted by the associated values, you could use sorted()
like this:
>>> keys = sorted(A, key=lambda k: (A[k][0], -A[k][1]))
>>> keys
['k1', 'k2', 'k3', 'k5', 'k4']
Python recently added an OrderedDict
http://docs.python.org/dev/library/collections.html#collections.OrderedDict
AFAIK dictionaries have no concept of "order"
You can not sort dicts - there is no ordering defined on dicts.
What about:
sorted(A, key = lambda x: (A[x][0], -A[x][1]))
At least it gives you the order for the keys.
Dictionaries are not sortable. You need may wish to use a list instead.
For example, your input could be represented as a list of tuples:
A=[('k3', ['b', 3]),('k2', ['a', 1]),('k1',['a', 3])...]
And we could sort it like so:
A=sorted(A, key=lambda x: (x[1][0], -x[1][1]))
精彩评论