Benno Benno - 1 year ago 131
Python Question

How to neatly print dictionaries with dictionaries inside

I use the following code:

sick = {"Carson": {"Reason": "Broken leg on P coy", "Expiry": "2017-1-4"}, "Jackson": {"Reason": "Fell over tree root on exercise", "Expiry": "2017-2-3"}, "Ben": {"Reason": "Tripped", "Expiry": "2018-7-6"}}

def showsick():
print "=" * 10
print "Personnel on sick:"
for name, reason, expiry in sick.iteritems():
print name, ": ", reason, "\nSick chit expires: ", expiry, "\n"
print "=" * 10

To try and produce an output like this:

Carson: Broken leg on P coy
Sick chit expires: 2017-1-4

Jackson: Fell over tree root on exercise
Sick chit expires: 2017-2-3

Ben: Tripped
Sick chit expires: 2018-7-6

But I get "ValueError: need more than 2 values to unpack". I've tried a number of different things including playing with json (very briefly) and pprint (again briefly), as well as a few other little things. I can't make it work though

Answer Source

iteritems only produces two pairs - key and value - at a time, so you can't unpack into three items in that for loop.

Instead, you want to do:

for name in sick:
     print name, ": ", sick[name]['Reason']
     print "Sick chit expires: ", sick[name]['Expiry']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download