Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all nested dictionary values?

for k, v in d.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?

EDIT

How about this? It still only prints one thing.

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

Full Test Case

Dictionary:

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

Result:

xml : {u'config': {u'portstatus': {u'status': u'good'}, u'target': u'1'}, u'port': u'11'} 
like image 785
Takkun Avatar asked May 25 '12 14:05

Takkun


People also ask

How do you loop through all nested dictionary values for a for loop in python?

Iterate over all values of a nested dictionary in python For that we need to again call the items() function on such values and get another iterable sequence of pairs and then look for dict objects in those pairs too.

How do you make a nested dictionary loop in python?

To create a nested dictionary, simply pass dictionary key:value pair as keyword arguments to dict() Constructor. You can use dict() function along with the zip() function, to combine separate lists of keys and values obtained dynamically at runtime.

How do you break nested dictionaries in python?

In Python, we use “ del “ statement to delete elements from nested dictionary.


1 Answers

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.items():         if isinstance(v, dict):             myprint(v)         else:             print("{0} : {1}".format(k, v)) 
like image 194
Scharron Avatar answered Oct 17 '22 01:10

Scharron