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

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

问题描述

我有一个嵌套的字典,如下所示

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"}
        }
    },
}

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

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'])

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

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()不能那样工作。

keys()doesn't work that way.


键()

返回词典键的新视图

您的嵌套字典是一个完全独立的字典,您可以使用自己的 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天全站免登陆