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

  • A+
Category:Languages

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 

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: