How to iterate through a nested dict?

I have a nested data structure python dictionary. I want to read its keys and values withoutusing a module collection. The data structure is similar to the one below.

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

I tried to read the keys in the dictionary using the following method, but getting an error.

the code

for key, value in d:
    print(Key)

Error

ValueError: too many values to unpack (expected 2)

So can someone explain the cause of the error and how to iterate through the dictionary.

+10
source share
4 answers

Like the requested output, the code looks 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

Instead, iteritems()you can also use items(), but it is iteritems()much more efficient and returns an iterator.

Hope this helps :)

+8
source

keys() ,

:

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

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

:

dict1 
foo
bar

dict2
baz 
quux

i , j .

+6

, dict.items():

for key, value in d.items():
    print(key)

:

for key in d:
    print(key)
+5

.

python , -, ( , (key,value), ( key ).

key, key, NameError.

for key in d:
    print(key)

.

+3

Source: https://habr.com/ru/post/1676223/


All Articles