ranjan
ranjan

Reputation: 61

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?

Upvotes: 1

Views: 113

Answers (6)

foosion
foosion

Reputation: 7898

Python recently added an OrderedDict

http://docs.python.org/dev/library/collections.html#collections.OrderedDict

Upvotes: 1

Steve Mayne
Steve Mayne

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

julx
julx

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

sth
sth

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

user2665694
user2665694

Reputation:

You can not sort dicts - there is no ordering defined on dicts.

Upvotes: 0

Joril
Joril

Reputation: 20547

AFAIK dictionaries have no concept of "order"

Upvotes: 0

Related Questions