Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...