简体   繁体   中英

How to print the keys from another dictionary and value from deep nested dict in Python

My Dictionary is below.How to print the keys from another dictionary and value from deep nested dict in 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']
filtered_map_dict = {'peers':'pe', 'remote_id':'id', 'remote_as':'as', 'uptime':'up'}
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)

My Output:

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

Expected output:

pe: 15.1.1.1
id: 15.1.1.1
as: 65002
up: 13002

You need to print filter_list[k] instead of simple k . I have written an example code which provides the expected output.

Code:

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


seek_keys(my_nested_dict, filtered_list, filtered_map_dict)

Output:

>>> python3 test.py 
pe: 15.1.1.1
id: 15.1.1.1
as: 65002
as: 13002  # It should be "as" based on your filtered_map_dict. (Not "up" as you have written in your question.)

If you change your filtered_map_dict to:

filtered_map_dict = {"peers": "pe", "remote_id": "id", "remote_as": "as", "uptime": "up"}

The output will be exactly what you want as you can see below.

>>> python3 test.py 
pe: 15.1.1.1
id: 15.1.1.1
as: 65002
up: 13002

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM