Doppel - 10 months ago 40
Python Question

# nested dictionary sorting

I've been trying to figure out how to sort these dictionaries:

`d1`
and
`d2`
inside the dictionary
`d3`
.

``````d1 = {'eggs':1, 'cheese':1}
d2 = {'cake':1, 'cream':1}
d3 = {'breakfast':{},'dessert':{}}
d3['breakfast'] = d1
d3['dessert'] = d2
for k,v in sorted(d3.items()):
for k,v in sorted(d3['breakfast'].items()):
for k,v in sorted(d3.items()):
print(k,v)
``````

This is the output:

``````breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
breakfast {'eggs': 1, 'cheese': 1}
dessert {'cream': 1, 'cake': 1}
``````

It sorts the two
`breakfast`
and
`dessert`
correctly, then inside
`dessert`
,
`'cream'`
and
`'eggs'`
are in the wrong order.

It should be:

``````dessert {'cake':1, 'cream':1}
``````

and it also prints the "sorted" dictionary
`d3`
four times, and I'm not exactly sure why.

For all I know, there could be a more effective way to be doing this, so any information is welcome.

So your algorithm has a few problems, mostly that you're nesting way too many times and looping over the same thing each time. Here's a better algorithm:

``````for k,v in sorted(d3.items()):
print(k + ":")
for k2,v2 in sorted(v.items()):
print("\t" + k2 + ", " + str(v2))
``````

It formats the answer like this:

``````breakfast:
cheese, 1
eggs, 1
dessert:
cake, 1
cream, 1
``````

I wasn't sure what your intended format is - hopefully you can modify it to be what you'd like. As you can see, this time the loop iterates first over d3, then over the elements of d3, rather than d3 again. This means that you'll go another level deep in the nested dictionary, rather than what you were doing before which was printing the same dictionary multiple times.

Source (Stackoverflow)