Reputation: 61
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?
Upvotes: 1
Views: 113
Reputation: 7898
Python recently added an OrderedDict
http://docs.python.org/dev/library/collections.html#collections.OrderedDict
Upvotes: 1
Reputation: 22818
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]))
Upvotes: 0
Reputation: 9091
What about:
sorted(A, key = lambda x: (A[x][0], -A[x][1]))
At least it gives you the order for the keys.
Upvotes: 0
Reputation: 229603
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']
Upvotes: 2