Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print specific keys and values from a deep nested dictionary in python 3.X

I am new to python and I've tried to search but can seem to find a sample of what I am trying to accomplish. Any ideas are much appreciated. I am working with a nested dictionary with lots of key and values but I only want to print specific ones using a filtered list variable.

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

I would like to a filter through it and choose which keys and values to print out

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

and achieve a out out of

peers: 15.1.1.1
remote_id: 15.1.1.1
remote_as: 65002
uptime: 13002
like image 753
JHCTac Avatar asked Dec 30 '18 05:12

JHCTac


People also ask

How do you fetch and display only the values of a dictionary in Python?

Python dictionary | values()If you use the type() method on the return value, you get “dict_values object”. It must be cast to obtain the actual list. Returns: returns a list of all the values available in a given dictionary.

What dictionary method is used to return a dictionary with the specified keys and values?

In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Parameters: This method takes no parameters. Returns: A view object that displays a list of a given dictionary's (key, value) tuple pair.


Video Answer


1 Answers

Use recursion and 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)

Note: There is a built in assumption here that if you ever want the "value" from a key whose value is another dictionary, you get the first key.

like image 105
JacobIRR Avatar answered Sep 19 '22 19:09

JacobIRR