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












9















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



























    9















    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

























      9












      9








      9


      1






      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 Dec 30 '18 at 5:02









      JHCTacJHCTac

      789




      789
























          5 Answers
          5






          active

          oldest

          votes


















          12














          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
            Dec 30 '18 at 5:24








          • 1





            Nice answer man.

            – U9-Forward
            Dec 30 '18 at 5:24






          • 1





            @JHCTac Now i edited for Jacob

            – U9-Forward
            Dec 30 '18 at 5:25











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

            – JHCTac
            Dec 30 '18 at 5:29






          • 1





            @JHCTac Nice to help,

            – U9-Forward
            Dec 30 '18 at 5:30



















          0














          On top of @JacobIRR;s answer, I would say you can try caching the recursed data in a flat dict. That way, it will be much faster than recurse every time. You need not worry about memory since the values in the flat dict will simply refer to the original objects in the deep dictionary. I will leave the modification of JacobIRR's code to you :).






          share|improve this answer































            0














            @JacobIRR has posted a great answer, but since you are attempting to join the matching keys with the its corresponding value, a much shorter solution arises:



            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"}}
            _list = ['peers', 'remote_id', 'remote_as', 'uptime']

            def _join(a, b):
            return '{}:{}n'.format(a, _keys(b, True) if isinstance(b, dict) else b)

            def _keys(_d, flag = False):
            return ''.join(_join(a, b) if a in _list else (a+'n' if flag else '')+_keys(b)
            for a, b in _d.items())

            print(get_keys(my_nested_dict))


            Output:



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





            share|improve this answer































              0














              In Python 3 it's more efficient and simpler to use generators instead of recursion:



              from typing import Any, Tuple, Generator, FrozenSet

              def search_in_dict(d: Any, keys: FrozenSet[str]) -> Generator[Tuple[str, Any], None, None]:
              """
              Generate pairs key-value for found keys
              """
              if not isinstance(d, dict):
              return
              for key, value in d.items():
              if key in keys:
              if isinstance(value, dict):
              # Special case: return the first key from nested dict as value
              yield key, tuple(value.keys())[0]
              else:
              yield key, value
              # continue to search deeper
              yield from search_in_dict(value, keys)


              and then fold it to dict again:



              flatten_dict_with_results = dict(kv for kv in search_in_dict(my_nested_dict, keys=frozenset(filtered_list)))





              share|improve this answer































                0














                You could use jsonparse_ng (pip install jsonparse-ng). Without the if/ else the value the the key "peers" is printed like it is (a dict).



                from jsonpath_ng.ext import parse

                my_nested_dict = {
                "global": {
                "peers": {
                "15.1.1.1": {
                "address_family": {
                "ipv4": {
                "accepted_prefixes": 4,
                "received_prefixes": 4,
                "sent_prefixes": 1
                }
                },
                "description": "== R3 BGP Neighbor ==",
                "is_enabled": true,
                "is_up": true,
                "local_as": 65002,
                "remote_as": 65002,
                "remote_id": "15.1.1.1",
                "uptime": 13002
                }
                },
                "router_id": "15.1.1.2"
                }
                }
                filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

                for list_item in filtered_list:
                found = parse(f'$..{list_item}').find(my_nested_dict)
                if found:
                if list_item == 'peers':
                print(f'{list_item} - {"".join(found[0].value.keys())}')
                else:
                print(f'{list_item} - {found[0].value}')





                share|improve this answer

























                  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

























                  5 Answers
                  5






                  active

                  oldest

                  votes








                  5 Answers
                  5






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  12














                  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
                    Dec 30 '18 at 5:24








                  • 1





                    Nice answer man.

                    – U9-Forward
                    Dec 30 '18 at 5:24






                  • 1





                    @JHCTac Now i edited for Jacob

                    – U9-Forward
                    Dec 30 '18 at 5:25











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

                    – JHCTac
                    Dec 30 '18 at 5:29






                  • 1





                    @JHCTac Nice to help,

                    – U9-Forward
                    Dec 30 '18 at 5:30
















                  12














                  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
                    Dec 30 '18 at 5:24








                  • 1





                    Nice answer man.

                    – U9-Forward
                    Dec 30 '18 at 5:24






                  • 1





                    @JHCTac Now i edited for Jacob

                    – U9-Forward
                    Dec 30 '18 at 5:25











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

                    – JHCTac
                    Dec 30 '18 at 5:29






                  • 1





                    @JHCTac Nice to help,

                    – U9-Forward
                    Dec 30 '18 at 5:30














                  12












                  12








                  12







                  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 Dec 30 '18 at 5:24









                  U9-Forward

                  14.5k21338




                  14.5k21338










                  answered Dec 30 '18 at 5:10









                  JacobIRRJacobIRR

                  3,39521228




                  3,39521228













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

                    – JHCTac
                    Dec 30 '18 at 5:24








                  • 1





                    Nice answer man.

                    – U9-Forward
                    Dec 30 '18 at 5:24






                  • 1





                    @JHCTac Now i edited for Jacob

                    – U9-Forward
                    Dec 30 '18 at 5:25











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

                    – JHCTac
                    Dec 30 '18 at 5:29






                  • 1





                    @JHCTac Nice to help,

                    – U9-Forward
                    Dec 30 '18 at 5:30



















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

                    – JHCTac
                    Dec 30 '18 at 5:24








                  • 1





                    Nice answer man.

                    – U9-Forward
                    Dec 30 '18 at 5:24






                  • 1





                    @JHCTac Now i edited for Jacob

                    – U9-Forward
                    Dec 30 '18 at 5:25











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

                    – JHCTac
                    Dec 30 '18 at 5:29






                  • 1





                    @JHCTac Nice to help,

                    – U9-Forward
                    Dec 30 '18 at 5:30

















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

                  – JHCTac
                  Dec 30 '18 at 5:24







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

                  – JHCTac
                  Dec 30 '18 at 5:24






                  1




                  1





                  Nice answer man.

                  – U9-Forward
                  Dec 30 '18 at 5:24





                  Nice answer man.

                  – U9-Forward
                  Dec 30 '18 at 5:24




                  1




                  1





                  @JHCTac Now i edited for Jacob

                  – U9-Forward
                  Dec 30 '18 at 5:25





                  @JHCTac Now i edited for Jacob

                  – U9-Forward
                  Dec 30 '18 at 5:25













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

                  – JHCTac
                  Dec 30 '18 at 5:29





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

                  – JHCTac
                  Dec 30 '18 at 5:29




                  1




                  1





                  @JHCTac Nice to help,

                  – U9-Forward
                  Dec 30 '18 at 5:30





                  @JHCTac Nice to help,

                  – U9-Forward
                  Dec 30 '18 at 5:30













                  0














                  On top of @JacobIRR;s answer, I would say you can try caching the recursed data in a flat dict. That way, it will be much faster than recurse every time. You need not worry about memory since the values in the flat dict will simply refer to the original objects in the deep dictionary. I will leave the modification of JacobIRR's code to you :).






                  share|improve this answer




























                    0














                    On top of @JacobIRR;s answer, I would say you can try caching the recursed data in a flat dict. That way, it will be much faster than recurse every time. You need not worry about memory since the values in the flat dict will simply refer to the original objects in the deep dictionary. I will leave the modification of JacobIRR's code to you :).






                    share|improve this answer


























                      0












                      0








                      0







                      On top of @JacobIRR;s answer, I would say you can try caching the recursed data in a flat dict. That way, it will be much faster than recurse every time. You need not worry about memory since the values in the flat dict will simply refer to the original objects in the deep dictionary. I will leave the modification of JacobIRR's code to you :).






                      share|improve this answer













                      On top of @JacobIRR;s answer, I would say you can try caching the recursed data in a flat dict. That way, it will be much faster than recurse every time. You need not worry about memory since the values in the flat dict will simply refer to the original objects in the deep dictionary. I will leave the modification of JacobIRR's code to you :).







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 30 '18 at 12:07









                      KarthikeyanKarthikeyan

                      1




                      1























                          0














                          @JacobIRR has posted a great answer, but since you are attempting to join the matching keys with the its corresponding value, a much shorter solution arises:



                          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"}}
                          _list = ['peers', 'remote_id', 'remote_as', 'uptime']

                          def _join(a, b):
                          return '{}:{}n'.format(a, _keys(b, True) if isinstance(b, dict) else b)

                          def _keys(_d, flag = False):
                          return ''.join(_join(a, b) if a in _list else (a+'n' if flag else '')+_keys(b)
                          for a, b in _d.items())

                          print(get_keys(my_nested_dict))


                          Output:



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





                          share|improve this answer




























                            0














                            @JacobIRR has posted a great answer, but since you are attempting to join the matching keys with the its corresponding value, a much shorter solution arises:



                            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"}}
                            _list = ['peers', 'remote_id', 'remote_as', 'uptime']

                            def _join(a, b):
                            return '{}:{}n'.format(a, _keys(b, True) if isinstance(b, dict) else b)

                            def _keys(_d, flag = False):
                            return ''.join(_join(a, b) if a in _list else (a+'n' if flag else '')+_keys(b)
                            for a, b in _d.items())

                            print(get_keys(my_nested_dict))


                            Output:



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





                            share|improve this answer


























                              0












                              0








                              0







                              @JacobIRR has posted a great answer, but since you are attempting to join the matching keys with the its corresponding value, a much shorter solution arises:



                              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"}}
                              _list = ['peers', 'remote_id', 'remote_as', 'uptime']

                              def _join(a, b):
                              return '{}:{}n'.format(a, _keys(b, True) if isinstance(b, dict) else b)

                              def _keys(_d, flag = False):
                              return ''.join(_join(a, b) if a in _list else (a+'n' if flag else '')+_keys(b)
                              for a, b in _d.items())

                              print(get_keys(my_nested_dict))


                              Output:



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





                              share|improve this answer













                              @JacobIRR has posted a great answer, but since you are attempting to join the matching keys with the its corresponding value, a much shorter solution arises:



                              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"}}
                              _list = ['peers', 'remote_id', 'remote_as', 'uptime']

                              def _join(a, b):
                              return '{}:{}n'.format(a, _keys(b, True) if isinstance(b, dict) else b)

                              def _keys(_d, flag = False):
                              return ''.join(_join(a, b) if a in _list else (a+'n' if flag else '')+_keys(b)
                              for a, b in _d.items())

                              print(get_keys(my_nested_dict))


                              Output:



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






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Dec 30 '18 at 16:44









                              Ajax1234Ajax1234

                              41.1k42853




                              41.1k42853























                                  0














                                  In Python 3 it's more efficient and simpler to use generators instead of recursion:



                                  from typing import Any, Tuple, Generator, FrozenSet

                                  def search_in_dict(d: Any, keys: FrozenSet[str]) -> Generator[Tuple[str, Any], None, None]:
                                  """
                                  Generate pairs key-value for found keys
                                  """
                                  if not isinstance(d, dict):
                                  return
                                  for key, value in d.items():
                                  if key in keys:
                                  if isinstance(value, dict):
                                  # Special case: return the first key from nested dict as value
                                  yield key, tuple(value.keys())[0]
                                  else:
                                  yield key, value
                                  # continue to search deeper
                                  yield from search_in_dict(value, keys)


                                  and then fold it to dict again:



                                  flatten_dict_with_results = dict(kv for kv in search_in_dict(my_nested_dict, keys=frozenset(filtered_list)))





                                  share|improve this answer




























                                    0














                                    In Python 3 it's more efficient and simpler to use generators instead of recursion:



                                    from typing import Any, Tuple, Generator, FrozenSet

                                    def search_in_dict(d: Any, keys: FrozenSet[str]) -> Generator[Tuple[str, Any], None, None]:
                                    """
                                    Generate pairs key-value for found keys
                                    """
                                    if not isinstance(d, dict):
                                    return
                                    for key, value in d.items():
                                    if key in keys:
                                    if isinstance(value, dict):
                                    # Special case: return the first key from nested dict as value
                                    yield key, tuple(value.keys())[0]
                                    else:
                                    yield key, value
                                    # continue to search deeper
                                    yield from search_in_dict(value, keys)


                                    and then fold it to dict again:



                                    flatten_dict_with_results = dict(kv for kv in search_in_dict(my_nested_dict, keys=frozenset(filtered_list)))





                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      In Python 3 it's more efficient and simpler to use generators instead of recursion:



                                      from typing import Any, Tuple, Generator, FrozenSet

                                      def search_in_dict(d: Any, keys: FrozenSet[str]) -> Generator[Tuple[str, Any], None, None]:
                                      """
                                      Generate pairs key-value for found keys
                                      """
                                      if not isinstance(d, dict):
                                      return
                                      for key, value in d.items():
                                      if key in keys:
                                      if isinstance(value, dict):
                                      # Special case: return the first key from nested dict as value
                                      yield key, tuple(value.keys())[0]
                                      else:
                                      yield key, value
                                      # continue to search deeper
                                      yield from search_in_dict(value, keys)


                                      and then fold it to dict again:



                                      flatten_dict_with_results = dict(kv for kv in search_in_dict(my_nested_dict, keys=frozenset(filtered_list)))





                                      share|improve this answer













                                      In Python 3 it's more efficient and simpler to use generators instead of recursion:



                                      from typing import Any, Tuple, Generator, FrozenSet

                                      def search_in_dict(d: Any, keys: FrozenSet[str]) -> Generator[Tuple[str, Any], None, None]:
                                      """
                                      Generate pairs key-value for found keys
                                      """
                                      if not isinstance(d, dict):
                                      return
                                      for key, value in d.items():
                                      if key in keys:
                                      if isinstance(value, dict):
                                      # Special case: return the first key from nested dict as value
                                      yield key, tuple(value.keys())[0]
                                      else:
                                      yield key, value
                                      # continue to search deeper
                                      yield from search_in_dict(value, keys)


                                      and then fold it to dict again:



                                      flatten_dict_with_results = dict(kv for kv in search_in_dict(my_nested_dict, keys=frozenset(filtered_list)))






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 12 at 4:21









                                      denexdenex

                                      614




                                      614























                                          0














                                          You could use jsonparse_ng (pip install jsonparse-ng). Without the if/ else the value the the key "peers" is printed like it is (a dict).



                                          from jsonpath_ng.ext import parse

                                          my_nested_dict = {
                                          "global": {
                                          "peers": {
                                          "15.1.1.1": {
                                          "address_family": {
                                          "ipv4": {
                                          "accepted_prefixes": 4,
                                          "received_prefixes": 4,
                                          "sent_prefixes": 1
                                          }
                                          },
                                          "description": "== R3 BGP Neighbor ==",
                                          "is_enabled": true,
                                          "is_up": true,
                                          "local_as": 65002,
                                          "remote_as": 65002,
                                          "remote_id": "15.1.1.1",
                                          "uptime": 13002
                                          }
                                          },
                                          "router_id": "15.1.1.2"
                                          }
                                          }
                                          filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

                                          for list_item in filtered_list:
                                          found = parse(f'$..{list_item}').find(my_nested_dict)
                                          if found:
                                          if list_item == 'peers':
                                          print(f'{list_item} - {"".join(found[0].value.keys())}')
                                          else:
                                          print(f'{list_item} - {found[0].value}')





                                          share|improve this answer






























                                            0














                                            You could use jsonparse_ng (pip install jsonparse-ng). Without the if/ else the value the the key "peers" is printed like it is (a dict).



                                            from jsonpath_ng.ext import parse

                                            my_nested_dict = {
                                            "global": {
                                            "peers": {
                                            "15.1.1.1": {
                                            "address_family": {
                                            "ipv4": {
                                            "accepted_prefixes": 4,
                                            "received_prefixes": 4,
                                            "sent_prefixes": 1
                                            }
                                            },
                                            "description": "== R3 BGP Neighbor ==",
                                            "is_enabled": true,
                                            "is_up": true,
                                            "local_as": 65002,
                                            "remote_as": 65002,
                                            "remote_id": "15.1.1.1",
                                            "uptime": 13002
                                            }
                                            },
                                            "router_id": "15.1.1.2"
                                            }
                                            }
                                            filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

                                            for list_item in filtered_list:
                                            found = parse(f'$..{list_item}').find(my_nested_dict)
                                            if found:
                                            if list_item == 'peers':
                                            print(f'{list_item} - {"".join(found[0].value.keys())}')
                                            else:
                                            print(f'{list_item} - {found[0].value}')





                                            share|improve this answer




























                                              0












                                              0








                                              0







                                              You could use jsonparse_ng (pip install jsonparse-ng). Without the if/ else the value the the key "peers" is printed like it is (a dict).



                                              from jsonpath_ng.ext import parse

                                              my_nested_dict = {
                                              "global": {
                                              "peers": {
                                              "15.1.1.1": {
                                              "address_family": {
                                              "ipv4": {
                                              "accepted_prefixes": 4,
                                              "received_prefixes": 4,
                                              "sent_prefixes": 1
                                              }
                                              },
                                              "description": "== R3 BGP Neighbor ==",
                                              "is_enabled": true,
                                              "is_up": true,
                                              "local_as": 65002,
                                              "remote_as": 65002,
                                              "remote_id": "15.1.1.1",
                                              "uptime": 13002
                                              }
                                              },
                                              "router_id": "15.1.1.2"
                                              }
                                              }
                                              filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

                                              for list_item in filtered_list:
                                              found = parse(f'$..{list_item}').find(my_nested_dict)
                                              if found:
                                              if list_item == 'peers':
                                              print(f'{list_item} - {"".join(found[0].value.keys())}')
                                              else:
                                              print(f'{list_item} - {found[0].value}')





                                              share|improve this answer















                                              You could use jsonparse_ng (pip install jsonparse-ng). Without the if/ else the value the the key "peers" is printed like it is (a dict).



                                              from jsonpath_ng.ext import parse

                                              my_nested_dict = {
                                              "global": {
                                              "peers": {
                                              "15.1.1.1": {
                                              "address_family": {
                                              "ipv4": {
                                              "accepted_prefixes": 4,
                                              "received_prefixes": 4,
                                              "sent_prefixes": 1
                                              }
                                              },
                                              "description": "== R3 BGP Neighbor ==",
                                              "is_enabled": true,
                                              "is_up": true,
                                              "local_as": 65002,
                                              "remote_as": 65002,
                                              "remote_id": "15.1.1.1",
                                              "uptime": 13002
                                              }
                                              },
                                              "router_id": "15.1.1.2"
                                              }
                                              }
                                              filtered_list = ['peers', 'remote_id', 'remote_as', 'uptime']

                                              for list_item in filtered_list:
                                              found = parse(f'$..{list_item}').find(my_nested_dict)
                                              if found:
                                              if list_item == 'peers':
                                              print(f'{list_item} - {"".join(found[0].value.keys())}')
                                              else:
                                              print(f'{list_item} - {found[0].value}')






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jan 14 at 12:42

























                                              answered Jan 13 at 13:56









                                              FransFrans

                                              1963




                                              1963






























                                                  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.




                                                  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

                                                  Monofisismo

                                                  Angular Downloading a file using contenturl with Basic Authentication

                                                  Olmecas