在 Python 中访问嵌套键 [英] Accessing nested keys in Python

查看:28
本文介绍了在 Python 中访问嵌套键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的嵌套字典

entry = {0: {"Q": 0},1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},2:{N":{Q":{E"}}},}

当我尝试仅访问密钥 1 的密钥时,我得到以下信息:

<预><代码>>>>打印(条目[1].keys())dict_keys(['W', 'E', 'N', 'S', 'Q'])

但是对于键 2,它只返回顶部键而不是嵌套键.

<预><代码>>>>打印(条目[2].keys())dict_keys(['N'])

为什么不返回字典的嵌套键?

解决方案

keys() 不能那样工作.

<块引用>

keys()

返回字典键的新视图

您的嵌套字典是一个完全独立的字典,您可以使用自己的 keys() 方法获取自己的键:

entry[2]['N'].keys()

如果要递归获取嵌套字典中的所有键,则必须为此实现一个方法:

entry = {0: {"Q": 0},1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},2:{N":{Q":{E"}}},}def rec_k​​eys(dictio):键 = []for (key,value) in dictio.items():如果是实例(值,字典):键.扩展(rec_k​​eys(值))别的:键.附加(键)返回键打印(rec_k​​eys(条目))# ['Q', 'Q', 'W', 'N', 'S', 'E', 'Q']

I have a nested dictionary as below

entry = {
    0: {"Q": 0},
    1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
    2: {
        "N": {
            "Q": {"E"}
        }
    },
}

When I try to access only the keys for the key 1, I get the following:

>>> print(entry[1].keys())
dict_keys(['W', 'E', 'N', 'S', 'Q'])

But for key 2 it only returns the top key and not the nested key.

>>> print(entry[2].keys())
dict_keys(['N'])  

Why is it not returning the nested key of the dictionary?

解决方案

keys()doesn't work that way.

keys()

Return a new view of the dictionary’s keys

Your nested dictionnary is a completely separate dict, and you can get its own keys with its own keys() method :

entry[2]['N'].keys()

If you want to recursively get all the keys inside nested dictionnaries, you will have to implement a method for that :

entry = {0: {"Q": 0},
         1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
         2: {"N": { "Q":{"E"}}},
}


def rec_keys(dictio):
    keys = []
    for (key,value) in dictio.items():
        if isinstance(value, dict):
            keys.extend(rec_keys(value))
        else:
            keys.append(key)
    return keys

print(rec_keys(entry))
# ['Q', 'Q', 'W', 'N', 'S', 'E', 'Q']

这篇关于在 Python 中访问嵌套键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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