python - 从 python 3.X 中的深层嵌套字典中打印特定键和值

标签 python python-3.x

我是 python 的新手,我尝试搜索但似乎可以找到我正在尝试完成的示例。非常感谢任何想法。我正在使用包含大量键和值的嵌套字典,但我只想使用过滤后的列表变量打印特定的键和值。

my_nested_dict = {"global": {"peers": {"15.1.1.1": {"remote_id": "15.1.1.1", "address_family": {"ipv4": {"sent_prefixes": 1, "received_prefixes": 4, "accepted_prefixes": 4}}, "remote_as": 65002, "uptime": 13002, "is_enabled": true, "is_up": true, "description": "== R3 BGP Neighbor ==", "local_as": 65002}}, "router_id": "15.1.1.2"}}

我想过滤它并选择要打印的键和值

filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

并实现一出一出

peers: 15.1.1.1
remote_id: 15.1.1.1
remote_as: 65002
uptime: 13002

最佳答案

使用递归和isinstance:

my_nested_dict = {"global": {"peers": {"15.1.1.1": {"remote_id": "15.1.1.1", "address_family": {"ipv4": {"sent_prefixes": 1, "received_prefixes": 4, "accepted_prefixes": 4}}, "remote_as": 65002, "uptime": 13002, "is_enabled": True, "is_up": True, "description": "== R3 BGP Neighbor ==", "local_as": 65002}}, "router_id": "15.1.1.2"}}

filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

def seek_keys(d, key_list):
    for k, v in d.items():
        if k in key_list:
            if isinstance(v, dict):
                print(k + ": " + list(v.keys())[0])
            else:
                print(k + ": " + str(v))
        if isinstance(v, dict):
            seek_keys(v, key_list)

seek_keys(my_nested_dict, filtered_list)

注意:这里有一个内置的假设,如果您想要从一个值为另一个字典的键中获取“值”,您将获得第一个键。

关于python - 从 python 3.X 中的深层嵌套字典中打印特定键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975391/

相关文章:

python - 无法使用 Python 的 vs code '' 更好的注释扩展''

javascript - 如何使用脚本标签下的url标签

python-3.x - 皮查姆-找不到声明去

python - 为什么我的 python 程序无法启动 pygame?

python - 如何告诉pbr在包中包含非代码文件

python - 403 权限缺失或不足

python - 无论如何,我可以在 Airflow 中设置运行我的代码的工作目录吗?

python - Pandas 将函数应用于列列表会引发 TypeError

python - Utf-8 与 sqlalchemy 在具有 init connect 的数据库上

python - lxml etree.parse 与参数一起使用时不起作用