社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python通过深层嵌套dict中的特定键获取所有值

achraf karoui • 3 年前 • 1164 次点击  
{
    "id": 1,
    "name": "Test",
    "fils": [
        {"id": 2, "name": "Test", "fils": []},
        {"id": 4, "name": "Test", "fils": []},
        {
            "id": 5,
            "name": "Test",
            "fils": [
                {
                    "id": 12,
                    "name": "Test",
                    "fils": [{"id": 14, "name": "test", "fils": []}],
                }
            ],
        },
    ],
}

所以我的目标是得到所有的id,它们是[1,2,4,5,12,14]。 有没有什么方法可以通过递归函数或其他方式实现呢?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131733
 
1164 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Andrej Kesely
Reply   •   1 楼
Andrej Kesely    3 年前

可以使用递归。如果 dct 你的字典是从问题中提取的吗

def get_ids(d):
    if isinstance(d, dict):
        for k, v in d.items():
            if k == "id":
                yield v
            else:
                yield from get_ids(v)
    elif isinstance(d, list):
        for v in d:
            yield from get_ids(v)


ids = list(get_ids(dct))
print(ids)

印刷品:

[1, 2, 4, 5, 12, 14]