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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With