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












6














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









share|improve this question



























    6














    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









    share|improve this question

























      6












      6








      6


      0





      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









      share|improve this question













      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 python-3.x






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 4 hours ago









      JHCTac

      585




      585
























          1 Answer
          1






          active

          oldest

          votes


















          8














          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.






          share|improve this answer























          • Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
            – JHCTac
            4 hours ago








          • 1




            Nice answer man.
            – U9-Forward
            4 hours ago






          • 1




            @JHCTac Now i edited for Jacob
            – U9-Forward
            4 hours ago










          • Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
            – JHCTac
            4 hours ago






          • 1




            @JHCTac Nice to help,
            – U9-Forward
            4 hours ago











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53975391%2fprint-specific-keys-and-values-from-a-deep-nested-dictionary-in-python-3-x%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          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.






          share|improve this answer























          • Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
            – JHCTac
            4 hours ago








          • 1




            Nice answer man.
            – U9-Forward
            4 hours ago






          • 1




            @JHCTac Now i edited for Jacob
            – U9-Forward
            4 hours ago










          • Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
            – JHCTac
            4 hours ago






          • 1




            @JHCTac Nice to help,
            – U9-Forward
            4 hours ago
















          8














          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.






          share|improve this answer























          • Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
            – JHCTac
            4 hours ago








          • 1




            Nice answer man.
            – U9-Forward
            4 hours ago






          • 1




            @JHCTac Now i edited for Jacob
            – U9-Forward
            4 hours ago










          • Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
            – JHCTac
            4 hours ago






          • 1




            @JHCTac Nice to help,
            – U9-Forward
            4 hours ago














          8












          8








          8






          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.






          share|improve this answer














          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 4 hours ago









          U9-Forward

          12.8k21136




          12.8k21136










          answered 4 hours ago









          JacobIRR

          3,22521027




          3,22521027












          • Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
            – JHCTac
            4 hours ago








          • 1




            Nice answer man.
            – U9-Forward
            4 hours ago






          • 1




            @JHCTac Now i edited for Jacob
            – U9-Forward
            4 hours ago










          • Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
            – JHCTac
            4 hours ago






          • 1




            @JHCTac Nice to help,
            – U9-Forward
            4 hours ago


















          • Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
            – JHCTac
            4 hours ago








          • 1




            Nice answer man.
            – U9-Forward
            4 hours ago






          • 1




            @JHCTac Now i edited for Jacob
            – U9-Forward
            4 hours ago










          • Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
            – JHCTac
            4 hours ago






          • 1




            @JHCTac Nice to help,
            – U9-Forward
            4 hours ago
















          Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
          – JHCTac
          4 hours ago






          Hi Jacob I tried that code however I am getting the following error: TypeError: 'dict_keys' object does not support indexing
          – JHCTac
          4 hours ago






          1




          1




          Nice answer man.
          – U9-Forward
          4 hours ago




          Nice answer man.
          – U9-Forward
          4 hours ago




          1




          1




          @JHCTac Now i edited for Jacob
          – U9-Forward
          4 hours ago




          @JHCTac Now i edited for Jacob
          – U9-Forward
          4 hours ago












          Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
          – JHCTac
          4 hours ago




          Wow that worked perfectly @U9-Forward and @JacobIRR! That is exactly what I was looking for.
          – JHCTac
          4 hours ago




          1




          1




          @JHCTac Nice to help,
          – U9-Forward
          4 hours ago




          @JHCTac Nice to help,
          – U9-Forward
          4 hours ago


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53975391%2fprint-specific-keys-and-values-from-a-deep-nested-dictionary-in-python-3-x%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Михайлов, Христо

          Гороховецкий артиллерийский полигон

          Центральная группа войск