如何遍历嵌套字典? [英] How to iterate through a nested dict?

查看:542
本文介绍了如何遍历嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的python dictionary数据结构.我想使用collection模块读取其键和值without.数据结构像下面这样.

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.

代码

for key, value in d:
    print(Key)

错误

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.

推荐答案

作为请求的输出,代码如下所示

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

您也可以使用items()代替iteritems(),但是iteritems()效率更高,并且返回迭代器.

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

希望这会有所帮助:)

这篇关于如何遍历嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆