Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a nested dict?

I have a nested python dictionary data structure. I want to read its keys and values without using collection module. The data structure is like bellow.

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

I was trying to read the keys in the dictionary using the bellow way but getting error.

Code

for key, value in d:
    print(Key)

Error

ValueError: too many values to unpack (expected 2)

So can anyone please explain the reason behind the error and how to iterate through the dictionary.

like image 789
Arijit Panda Avatar asked May 03 '17 06:05

Arijit Panda


People also ask

How do you iterate over nested dictionaries?

just write d. items() , it will work, by default on iterating the name of dict returns only the keys.

How do you navigate a nested dictionary in Python?

One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.

What does Iteritems do in Python?

The iteritems() method generates an iterator object of the DataFrame, allowing us to iterate each column of the DataFrame. Note: This method is the same as the items() method. Each iteration produces a label object and a column object. The label is the column name.


2 Answers

keys() method returns a view object that displays a list of all the keys in the dictionary

Iterate nested dictionary:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

for i in d.keys():
    print i
    for j in d[i].keys():
        print j

OR

for i in d:
    print i
    for j in d[i]:
        print j

output:

dict1 
foo
bar

dict2
baz 
quux

where i iterate main dictionary key and j iterate the nested dictionary key.

like image 53
bharatk Avatar answered Sep 22 '22 18:09

bharatk


As the requested output, the code goes like this

    d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

    for k1,v1 in d.iteritems(): # the basic way
        temp = ""   
        temp+=k1
        for k2,v2 in v1.iteritems():
           temp = temp+" "+str(k2)+" "+str(v2)
        print temp

In place of iteritems() you can use items() as well, but iteritems() is much more efficient and returns an iterator.

Hope this helps :)

like image 22
Sunil Lulla Avatar answered Sep 20 '22 18:09

Sunil Lulla