如何从嵌套字典中获取密钥? [英] How can I get the keys from a nested dictionary?

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

问题描述

我在字典中的字典中有一个列表:

I have a list within a dictionary within a dictionary:

{FirmA:{ProductA:[Color1,Color2,Color3]}}

我想从First Firm词典级别构建键列表.

I want to build a list of keys from the First Firm dictionary level.

然后,我需要基于公司密钥访问第二级产品字典.

Then, I need to access the second level Product dictionary based on a Firm Key.

最后,我需要根据词典"级别2(产品")中的产品"键访问颜色"列表.

Finally, I will need to access the Colors list based on the Product key from Dictionary level 2 (Products).

我试图获取Firms的1级密钥:

I tried to get the level 1 keys for Firms:

[i for i in dict.keys()]

返回

ValueError: Too many values to unpack

这是一个相当大的数据集.

This is a fairly large data set.

我还没有找到第二级字典.

I have not been able to get to the 2nd level dictionary yet.

推荐答案

那又怎么样:

d = {'foo':{'bar':42}}

# you can do much like for nested list, like so:
print(d['foo'])
print(d['foo']['bar'])

# or you can iterate:
for k,v in d.items():
    print(k,v)

    # if the value is also a dictionary, iterate on it again:
    try:
        for k2, v2 in v.items():
            if isinstance(v2, list):
                for el in v2:
                    print el
    except:
        pass

实际上,如果它是一个大数据集,并且实际上在字典的第一遍以下您将只有几个值,那么进行实例检查(isinstance(v, dict))可能也会更快,因为捕获成本很高.取决于细节...

actually if it's a large dataset, and you'll have few values below the first pass actually a dictionary, it may be faster to do an instance check as well (isinstance(v, dict)), since catching is expensive. Depends on the details....

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

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