Takkun Takkun - 9 months ago 138
Python Question

Loop through all nested dictionary values?

for k, v in dict.iteritems():
if type(v) is dict:
for t, c in v.iteritems():
print "{0} : {1}".format(t, c)

I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print out its key value pairs...etc. Any help?


How about this? It still only prints one thing.

def printDict(dict):
for k, v in dict.iteritems():
if type(v) is dict:
print "{0} : {1}".format(k, v)

Full Test Case


{u'xml': {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'},
u'port': u'11'}}


xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'}


As said by Niklas, you need recursion, i.e. you want to define a function to print your dict, and if the value is a dict, you want to call your print function using this new dict.

Something like :

def myprint(d):
  for k, v in d.iteritems():
    if isinstance(v, dict):
      print "{0} : {1}".format(k, v)