Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print dictionary when value is an object (Python)

myDict = {name1: object1, name2: object2, etc....}

*The objects look like this:

Color: Blue, Flies: True, etc...

EDIT: included above dictionary so you can see what I'm working with.

While researching how to print the preceding dictionary in a nice, readable fashion, I tried the following code:

for key in myDict:
        print (key)
        for value in myDict[key]:
            print (value, ":", myDict[key][value])

This would work, HOWEVER, my "value"'s are all OBJECTS and it says that it can't iterate (which makes sense). I just want to know how to make it work the way it would if the value was a list or something that was iterable.

My desired output format is something like this:

Item1:              --> Key (it's the name of the object)
Color: Blue         --> Value (this is object[0])
Flies: True         --> Value (this is object[1])
etc....

Thanks!

like image 555
AmericanMade Avatar asked Nov 22 '25 05:11

AmericanMade


1 Answers

You could just catch the TypeError that occurs when trying to iterate a noniterable (might want to make exceptions for strings though).

try:
    for value in myDict[key]:
        print (value, ":", myDict[key][value])
except TypeError:
   print value
like image 58
woot Avatar answered Nov 24 '25 22:11

woot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!