Dictionary that has lists in keys, how to print so that the KEY with the least values in the list gets printed first?

Go To StackoverFlow.com


So I have tried to do this extensively but to no avail.. I'm writting a program that takes a dictionary of names that have a list to them, and a numerical value of the amount of things in the list. I want to print each name in the list so that the first name that gets printed is the one with the least amount of values in the list, and the last name printed is the one with the most amount of values in the list.. here is my code. IT ONLY prints the name which is the key and then the whole list of values. and then it prints e which is the end. so

"anna" 3 4 5 6 e "dan" 3 4 6 e "cilla" 3 4 e "billy" 6 e ...and so on

for GPS in GNR:

    for s in GNR[GPS]:

and here is the dictionary with its values.

GNR = {"anna":[3,4,5,6],"billy":[6],"cilla":[3,4],"dan":[3,4,6]}

So the result I would like is not the above but this:

"billy" 6 e "cilla" 3 4 e "dan" 3 4 6 e "anna" 3 4 5 6 e

as you see it prints the name with the least values in its list first followed by the rest.

I'm clueless how to do this :( I know i need to compare each value to the rest and then save it somewhere but I dont know where. Any help will be appriciated :)

2012-04-04 01:25
by 2WeeksToGO


To get the keys ordered by number of elements in the corresponding list, you could do:

ascending = sorted(GNR, key=lambda x: len(GNR[x]))
# ascending is ['billy', 'cilla', 'dan', 'anna']

for key in ascending:
    li = GNR[key]
    # print them etc.
2012-04-04 01:41
by Preet Kukreti
THanx a lot that worked like a charm! : - 2WeeksToGO 2012-04-04 02:24
Can you look at my other post? It takes this and combined it with sorting alphabetically.. and its way over my head but its the last thing i need to do..

[link]http://stackoverflow.com/questions/10004264/python3-sort-a-dictionary-keys-from-left-to-right-according-to-alphabet-and-thei[/link - 2WeeksToGO 2012-04-04 02:45