### Sort a dictionary according to the lists size and then alphabetically by their key in Python?

4

So I have a tiny problem. I got help here a while ago about sorting a dictionary with keys that have a list to each key according to the value of things in the list. The keys with lists with the least amount of values on the left and to the right the keys with lists with the most amount of values. That worked great. Now I know how to sort dictionary keys alphabetically but I cant get it to work combined with the above..

I'm trying to sort the dictionary below according to first how many values the key list contains... and then alphabetically if the key list contains the same amount of values as a previous key list.

so before I would have this:

`Dict = {"anna":[1,2,3],"billy":[1,2],"cilla":[1,2,3,4],"cecillia":[1,2,3,4],"dan":[1]}`

And after if everything goes well I would like to have...

`Dict = {"dan":[1],"billy":[1,2],"anna":[1,2,3],"cecillia":[1,2,3,4],"cilla":[1,2,3,4]}`

As you see in the above, `cecillia` comes before `cilla` since they both have 4 values in their lists... and `dan` comes in first since he has the least amount of values in his list. I hope this makes sense. What I have right now to get the below result is:

`ascending = sorted(Dict, key =lambda x: len(Dict[x]))`

this gives me for example:

`{"dan":[1],"billy":[1,2],"anna":[1,2,3],"cilla":[1,2,3,4],"cecillia":[1,2,3,4]}`

So it works but only for the values in the list.. now when I go

`ascending.sort()`

it sorts the dictionary alphabetically but then the order of values from least to greatest is gone. Anyone know how to to combine the two things? I would greatly appreciate it.

2012-04-04 02:41
by 2WeeksToGO

4

You cannot keep dictionaries sorted so you must convert it to a list of tuples:

``````D = [ (x, Dict[x]) for x in Dict]
ascending = sorted(D, key = lambda x: x[1])
ascending.sort()
``````

See http://wiki.python.org/moin/HowTo/Sorting . BTW the feature you are relying on is in fact because the sorting algorithm is stable (which apparently was not the case when I was programming in Python).

2012-04-04 03:24