Remove keys from a nested dictionary if they appear elsewhere as a valueHow do I sort a list of dictionaries by a value of the dictionary?Sort a Map<Key, Value> by valuesGetting key with maximum value in dictionary?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryDelete an element from a dictionaryGet key by value in dictionaryHow can I sort a dictionary by key?How to remove a key from a Python dictionary?

How does mathematics work?

How to plot a crossection of a ParametricPlot3D?

Does Impedance Matching Imply any Practical RF Transmitter Must Waste >=50% of Energy?

Progressive key bindings

Why is the UH-60 tail rotor canted?

Higher calorie ice cream

Can we have too many dialogue tags and follow up actions?

What is "ass door"?

What does a black-and-white Puerto Rican flag signify?

Book in which the "mountain" in the distance was a hole in the flat world

Is the apartment I want to rent a scam?

Can I pay with HKD in Macau or Shenzhen?

Why can't a country print its own money to spend it only abroad?

Bounded Torsion, without Mazur’s Theorem

Does switching on an old games console without a cartridge damage it?

How am I supposed to put out fires?

Host telling me to cancel my booking in exchange for a discount?

What kind of curve (or model) should I fit to my percentage data?

What is the best word describing the nature of expiring in a short amount of time, connoting "losing public attention"?

My current job follows "worst practices". How can I talk about my experience in an interview without giving off red flags?

What is a plausible power source to indefinitely sustain a space station?

Are there any documented cases of extinction of a species of fungus?

What is "It is x o'clock" in Japanese with subject

Why does the salt in the oceans not sink to the bottom?



Remove keys from a nested dictionary if they appear elsewhere as a value


How do I sort a list of dictionaries by a value of the dictionary?Sort a Map<Key, Value> by valuesGetting key with maximum value in dictionary?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryDelete an element from a dictionaryGet key by value in dictionaryHow can I sort a dictionary by key?How to remove a key from a Python dictionary?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have a nested dictionary containing parents (keys) and their children (values). I want to remove parents and their children if the parent is a child of another parent in the tree, i.e. I want to delete a key if it appears elsewhere in the dictionary as a value. Here is example input/output:



Input:




"Animal":
"Cat": [],
"Dog":
"Labrador":
"LabradorPup": []


,
"DieselCar":
"Hyundai": []
,
"Dog":
"Labrador":
"LabradorPup": []

,
"ElectricCar":
"Tesla": []
,
"Labrador":
"LabradorPup": []
,
"PetrolCar":
"Ford": [],
"Hyundai": []
,
"Vehicle":
"DieselCar":
"Hyundai": []
,
"ElectricCar":
"Tesla": []
,
"PetrolCar":
"Ford": [],
"Hyundai": []





Desired output:




"Animal":
"Cat": [],
"Dog":
"Labrador":
"LabradorPup": []


,
"Vehicle":
"DieselCar":
"Hyundai": []
,
"ElectricCar":
"Tesla": []
,
"PetrolCar":
"Ford": [],
"Hyundai": []





I have the following code which keeps the parents who have children, however this doesn't produce the output I am looking for:



inheritance_tree = parent:children for parent, children in inheritance_tree.items() if any(child for child in children.values())


You can see that the "Dog" key is not removed even though it is a child of "Animal":




"Animal":
"Cat": [],
"Dog":
"Labrador":
"LabradorPup": []


,
"Dog":
"Labrador":
"LabradorPup": []

,
"Vehicle":
"DieselCar":
"Hyundai": []
,
"ElectricCar":
"Tesla": []
,
"PetrolCar":
"Ford": [],
"Hyundai": []












share|improve this question




























    1















    I have a nested dictionary containing parents (keys) and their children (values). I want to remove parents and their children if the parent is a child of another parent in the tree, i.e. I want to delete a key if it appears elsewhere in the dictionary as a value. Here is example input/output:



    Input:




    "Animal":
    "Cat": [],
    "Dog":
    "Labrador":
    "LabradorPup": []


    ,
    "DieselCar":
    "Hyundai": []
    ,
    "Dog":
    "Labrador":
    "LabradorPup": []

    ,
    "ElectricCar":
    "Tesla": []
    ,
    "Labrador":
    "LabradorPup": []
    ,
    "PetrolCar":
    "Ford": [],
    "Hyundai": []
    ,
    "Vehicle":
    "DieselCar":
    "Hyundai": []
    ,
    "ElectricCar":
    "Tesla": []
    ,
    "PetrolCar":
    "Ford": [],
    "Hyundai": []





    Desired output:




    "Animal":
    "Cat": [],
    "Dog":
    "Labrador":
    "LabradorPup": []


    ,
    "Vehicle":
    "DieselCar":
    "Hyundai": []
    ,
    "ElectricCar":
    "Tesla": []
    ,
    "PetrolCar":
    "Ford": [],
    "Hyundai": []





    I have the following code which keeps the parents who have children, however this doesn't produce the output I am looking for:



    inheritance_tree = parent:children for parent, children in inheritance_tree.items() if any(child for child in children.values())


    You can see that the "Dog" key is not removed even though it is a child of "Animal":




    "Animal":
    "Cat": [],
    "Dog":
    "Labrador":
    "LabradorPup": []


    ,
    "Dog":
    "Labrador":
    "LabradorPup": []

    ,
    "Vehicle":
    "DieselCar":
    "Hyundai": []
    ,
    "ElectricCar":
    "Tesla": []
    ,
    "PetrolCar":
    "Ford": [],
    "Hyundai": []












    share|improve this question
























      1












      1








      1


      0






      I have a nested dictionary containing parents (keys) and their children (values). I want to remove parents and their children if the parent is a child of another parent in the tree, i.e. I want to delete a key if it appears elsewhere in the dictionary as a value. Here is example input/output:



      Input:




      "Animal":
      "Cat": [],
      "Dog":
      "Labrador":
      "LabradorPup": []


      ,
      "DieselCar":
      "Hyundai": []
      ,
      "Dog":
      "Labrador":
      "LabradorPup": []

      ,
      "ElectricCar":
      "Tesla": []
      ,
      "Labrador":
      "LabradorPup": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []
      ,
      "Vehicle":
      "DieselCar":
      "Hyundai": []
      ,
      "ElectricCar":
      "Tesla": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []





      Desired output:




      "Animal":
      "Cat": [],
      "Dog":
      "Labrador":
      "LabradorPup": []


      ,
      "Vehicle":
      "DieselCar":
      "Hyundai": []
      ,
      "ElectricCar":
      "Tesla": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []





      I have the following code which keeps the parents who have children, however this doesn't produce the output I am looking for:



      inheritance_tree = parent:children for parent, children in inheritance_tree.items() if any(child for child in children.values())


      You can see that the "Dog" key is not removed even though it is a child of "Animal":




      "Animal":
      "Cat": [],
      "Dog":
      "Labrador":
      "LabradorPup": []


      ,
      "Dog":
      "Labrador":
      "LabradorPup": []

      ,
      "Vehicle":
      "DieselCar":
      "Hyundai": []
      ,
      "ElectricCar":
      "Tesla": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []












      share|improve this question














      I have a nested dictionary containing parents (keys) and their children (values). I want to remove parents and their children if the parent is a child of another parent in the tree, i.e. I want to delete a key if it appears elsewhere in the dictionary as a value. Here is example input/output:



      Input:




      "Animal":
      "Cat": [],
      "Dog":
      "Labrador":
      "LabradorPup": []


      ,
      "DieselCar":
      "Hyundai": []
      ,
      "Dog":
      "Labrador":
      "LabradorPup": []

      ,
      "ElectricCar":
      "Tesla": []
      ,
      "Labrador":
      "LabradorPup": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []
      ,
      "Vehicle":
      "DieselCar":
      "Hyundai": []
      ,
      "ElectricCar":
      "Tesla": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []





      Desired output:




      "Animal":
      "Cat": [],
      "Dog":
      "Labrador":
      "LabradorPup": []


      ,
      "Vehicle":
      "DieselCar":
      "Hyundai": []
      ,
      "ElectricCar":
      "Tesla": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []





      I have the following code which keeps the parents who have children, however this doesn't produce the output I am looking for:



      inheritance_tree = parent:children for parent, children in inheritance_tree.items() if any(child for child in children.values())


      You can see that the "Dog" key is not removed even though it is a child of "Animal":




      "Animal":
      "Cat": [],
      "Dog":
      "Labrador":
      "LabradorPup": []


      ,
      "Dog":
      "Labrador":
      "LabradorPup": []

      ,
      "Vehicle":
      "DieselCar":
      "Hyundai": []
      ,
      "ElectricCar":
      "Tesla": []
      ,
      "PetrolCar":
      "Ford": [],
      "Hyundai": []









      python python-2.7 dictionary nested






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 26 at 14:01









      GaryGary

      5410 bronze badges




      5410 bronze badges






















          3 Answers
          3






          active

          oldest

          votes


















          1














          inheritance_tree = 
          parent:children for parent, children in inheritance_tree.items() if any(
          child for child in children.values()
          )



          Any checks if the children has childrens of its own.
          So what your current code does is keep only the parents who have grand-children.
          If you wish to remove those children from the list, you can write a function that goes through the list , and modifies a copy of it.



          If you wish to stick to a one liner, you need to look for the parent in the values of the inheritance tree.
          However those values can be different from a dict, so you need to check for that as well.



          y= parent:children for parent, children in x.items() if all(
          [(parent not in set(k.keys())) for k in x.values() if k])






          share|improve this answer






























            1














            I don't think any(child for child in children.values()) is an effective way of determining whether children should stay in the final dict. That expression is basically equivalent to "does this dict have at least one value that isn't an empty string?". The Dog dict has a non-empty child, so it remains in your final dict.



            Here's the approach I would use. Write a function that recursively iterates over a nested data structure and yields all of its keys, no matter how deeply they are nested. Run this function on every top-level key-value pair to identify the names of all child values. Then create a new dict that excludes those names from the top level.



            def iter_all_keys(obj):
            if not isinstance(obj, dict):
            return
            for key, value in obj.items():
            yield key
            for x in iter_all_keys(value):
            yield x

            d =
            "Animal":
            "Cat": [],
            "Dog":
            "Labrador":
            "LabradorPup": []


            ,
            "DieselCar":
            "Hyundai": []
            ,
            "Dog":
            "Labrador":
            "LabradorPup": []

            ,
            "ElectricCar":
            "Tesla": []
            ,
            "Labrador":
            "LabradorPup": []
            ,
            "PetrolCar":
            "Ford": [],
            "Hyundai": []
            ,
            "Vehicle":
            "DieselCar":
            "Hyundai": []
            ,
            "ElectricCar":
            "Tesla": []
            ,
            "PetrolCar":
            "Ford": [],
            "Hyundai": []




            child_names = child_name for toplevel_name, toplevel_children in d.items() for child_name in iter_all_keys(toplevel_children)

            d = key: value for key, value in d.items() if key not in child_names
            print(d)


            Result (whitespace added by me for clarity):




            'Animal':
            'Dog':
            'Labrador':
            'LabradorPup': []

            ,
            'Cat': []
            ,
            'Vehicle':
            'DieselCar':
            'Hyundai': []
            ,
            'PetrolCar':
            'Hyundai': [],
            'Ford': []
            ,
            'ElectricCar':
            'Tesla': []





            Note that this only removes duplicates from the top level. If you were to run this code on a dictionary such as this one:



            d = 
            "Human":
            "Fred": [],
            "Barney": []
            ,
            "Caveman":
            "Fred": [],
            "Barney": []




            ... Then the resulting dict would be identical to the input. Fred and Barney both appear twice in the data structure. If this is not the desired result, it's not clear what the result should be. Should Fred and Barney be removed from Human, or from Caveman? If the logic should be "keep Fred and Barney in Human, because that's the one we encountered first. Get rid of the rest", then the result will not be deterministic, because dictionaries in 2.7 are not guaranteed to be ordered.






            share|improve this answer
































              0














              Try This:



              I Know its Complicated.



              aa = [i for i,j in a.items()]
              bb = [get_all_keys(j) for i,j in a.items()]

              for i in aa:
              for j in bb:
              if i in j:
              for k in a:
              if k==i:
              del a[k]


              Tell me you are getting right or wrong.






              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%2f55359039%2fremove-keys-from-a-nested-dictionary-if-they-appear-elsewhere-as-a-value%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1














                inheritance_tree = 
                parent:children for parent, children in inheritance_tree.items() if any(
                child for child in children.values()
                )



                Any checks if the children has childrens of its own.
                So what your current code does is keep only the parents who have grand-children.
                If you wish to remove those children from the list, you can write a function that goes through the list , and modifies a copy of it.



                If you wish to stick to a one liner, you need to look for the parent in the values of the inheritance tree.
                However those values can be different from a dict, so you need to check for that as well.



                y= parent:children for parent, children in x.items() if all(
                [(parent not in set(k.keys())) for k in x.values() if k])






                share|improve this answer



























                  1














                  inheritance_tree = 
                  parent:children for parent, children in inheritance_tree.items() if any(
                  child for child in children.values()
                  )



                  Any checks if the children has childrens of its own.
                  So what your current code does is keep only the parents who have grand-children.
                  If you wish to remove those children from the list, you can write a function that goes through the list , and modifies a copy of it.



                  If you wish to stick to a one liner, you need to look for the parent in the values of the inheritance tree.
                  However those values can be different from a dict, so you need to check for that as well.



                  y= parent:children for parent, children in x.items() if all(
                  [(parent not in set(k.keys())) for k in x.values() if k])






                  share|improve this answer

























                    1












                    1








                    1







                    inheritance_tree = 
                    parent:children for parent, children in inheritance_tree.items() if any(
                    child for child in children.values()
                    )



                    Any checks if the children has childrens of its own.
                    So what your current code does is keep only the parents who have grand-children.
                    If you wish to remove those children from the list, you can write a function that goes through the list , and modifies a copy of it.



                    If you wish to stick to a one liner, you need to look for the parent in the values of the inheritance tree.
                    However those values can be different from a dict, so you need to check for that as well.



                    y= parent:children for parent, children in x.items() if all(
                    [(parent not in set(k.keys())) for k in x.values() if k])






                    share|improve this answer













                    inheritance_tree = 
                    parent:children for parent, children in inheritance_tree.items() if any(
                    child for child in children.values()
                    )



                    Any checks if the children has childrens of its own.
                    So what your current code does is keep only the parents who have grand-children.
                    If you wish to remove those children from the list, you can write a function that goes through the list , and modifies a copy of it.



                    If you wish to stick to a one liner, you need to look for the parent in the values of the inheritance tree.
                    However those values can be different from a dict, so you need to check for that as well.



                    y= parent:children for parent, children in x.items() if all(
                    [(parent not in set(k.keys())) for k in x.values() if k])







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 26 at 14:28









                    Born Tbe WastedBorn Tbe Wasted

                    261 bronze badge




                    261 bronze badge























                        1














                        I don't think any(child for child in children.values()) is an effective way of determining whether children should stay in the final dict. That expression is basically equivalent to "does this dict have at least one value that isn't an empty string?". The Dog dict has a non-empty child, so it remains in your final dict.



                        Here's the approach I would use. Write a function that recursively iterates over a nested data structure and yields all of its keys, no matter how deeply they are nested. Run this function on every top-level key-value pair to identify the names of all child values. Then create a new dict that excludes those names from the top level.



                        def iter_all_keys(obj):
                        if not isinstance(obj, dict):
                        return
                        for key, value in obj.items():
                        yield key
                        for x in iter_all_keys(value):
                        yield x

                        d =
                        "Animal":
                        "Cat": [],
                        "Dog":
                        "Labrador":
                        "LabradorPup": []


                        ,
                        "DieselCar":
                        "Hyundai": []
                        ,
                        "Dog":
                        "Labrador":
                        "LabradorPup": []

                        ,
                        "ElectricCar":
                        "Tesla": []
                        ,
                        "Labrador":
                        "LabradorPup": []
                        ,
                        "PetrolCar":
                        "Ford": [],
                        "Hyundai": []
                        ,
                        "Vehicle":
                        "DieselCar":
                        "Hyundai": []
                        ,
                        "ElectricCar":
                        "Tesla": []
                        ,
                        "PetrolCar":
                        "Ford": [],
                        "Hyundai": []




                        child_names = child_name for toplevel_name, toplevel_children in d.items() for child_name in iter_all_keys(toplevel_children)

                        d = key: value for key, value in d.items() if key not in child_names
                        print(d)


                        Result (whitespace added by me for clarity):




                        'Animal':
                        'Dog':
                        'Labrador':
                        'LabradorPup': []

                        ,
                        'Cat': []
                        ,
                        'Vehicle':
                        'DieselCar':
                        'Hyundai': []
                        ,
                        'PetrolCar':
                        'Hyundai': [],
                        'Ford': []
                        ,
                        'ElectricCar':
                        'Tesla': []





                        Note that this only removes duplicates from the top level. If you were to run this code on a dictionary such as this one:



                        d = 
                        "Human":
                        "Fred": [],
                        "Barney": []
                        ,
                        "Caveman":
                        "Fred": [],
                        "Barney": []




                        ... Then the resulting dict would be identical to the input. Fred and Barney both appear twice in the data structure. If this is not the desired result, it's not clear what the result should be. Should Fred and Barney be removed from Human, or from Caveman? If the logic should be "keep Fred and Barney in Human, because that's the one we encountered first. Get rid of the rest", then the result will not be deterministic, because dictionaries in 2.7 are not guaranteed to be ordered.






                        share|improve this answer





























                          1














                          I don't think any(child for child in children.values()) is an effective way of determining whether children should stay in the final dict. That expression is basically equivalent to "does this dict have at least one value that isn't an empty string?". The Dog dict has a non-empty child, so it remains in your final dict.



                          Here's the approach I would use. Write a function that recursively iterates over a nested data structure and yields all of its keys, no matter how deeply they are nested. Run this function on every top-level key-value pair to identify the names of all child values. Then create a new dict that excludes those names from the top level.



                          def iter_all_keys(obj):
                          if not isinstance(obj, dict):
                          return
                          for key, value in obj.items():
                          yield key
                          for x in iter_all_keys(value):
                          yield x

                          d =
                          "Animal":
                          "Cat": [],
                          "Dog":
                          "Labrador":
                          "LabradorPup": []


                          ,
                          "DieselCar":
                          "Hyundai": []
                          ,
                          "Dog":
                          "Labrador":
                          "LabradorPup": []

                          ,
                          "ElectricCar":
                          "Tesla": []
                          ,
                          "Labrador":
                          "LabradorPup": []
                          ,
                          "PetrolCar":
                          "Ford": [],
                          "Hyundai": []
                          ,
                          "Vehicle":
                          "DieselCar":
                          "Hyundai": []
                          ,
                          "ElectricCar":
                          "Tesla": []
                          ,
                          "PetrolCar":
                          "Ford": [],
                          "Hyundai": []




                          child_names = child_name for toplevel_name, toplevel_children in d.items() for child_name in iter_all_keys(toplevel_children)

                          d = key: value for key, value in d.items() if key not in child_names
                          print(d)


                          Result (whitespace added by me for clarity):




                          'Animal':
                          'Dog':
                          'Labrador':
                          'LabradorPup': []

                          ,
                          'Cat': []
                          ,
                          'Vehicle':
                          'DieselCar':
                          'Hyundai': []
                          ,
                          'PetrolCar':
                          'Hyundai': [],
                          'Ford': []
                          ,
                          'ElectricCar':
                          'Tesla': []





                          Note that this only removes duplicates from the top level. If you were to run this code on a dictionary such as this one:



                          d = 
                          "Human":
                          "Fred": [],
                          "Barney": []
                          ,
                          "Caveman":
                          "Fred": [],
                          "Barney": []




                          ... Then the resulting dict would be identical to the input. Fred and Barney both appear twice in the data structure. If this is not the desired result, it's not clear what the result should be. Should Fred and Barney be removed from Human, or from Caveman? If the logic should be "keep Fred and Barney in Human, because that's the one we encountered first. Get rid of the rest", then the result will not be deterministic, because dictionaries in 2.7 are not guaranteed to be ordered.






                          share|improve this answer



























                            1












                            1








                            1







                            I don't think any(child for child in children.values()) is an effective way of determining whether children should stay in the final dict. That expression is basically equivalent to "does this dict have at least one value that isn't an empty string?". The Dog dict has a non-empty child, so it remains in your final dict.



                            Here's the approach I would use. Write a function that recursively iterates over a nested data structure and yields all of its keys, no matter how deeply they are nested. Run this function on every top-level key-value pair to identify the names of all child values. Then create a new dict that excludes those names from the top level.



                            def iter_all_keys(obj):
                            if not isinstance(obj, dict):
                            return
                            for key, value in obj.items():
                            yield key
                            for x in iter_all_keys(value):
                            yield x

                            d =
                            "Animal":
                            "Cat": [],
                            "Dog":
                            "Labrador":
                            "LabradorPup": []


                            ,
                            "DieselCar":
                            "Hyundai": []
                            ,
                            "Dog":
                            "Labrador":
                            "LabradorPup": []

                            ,
                            "ElectricCar":
                            "Tesla": []
                            ,
                            "Labrador":
                            "LabradorPup": []
                            ,
                            "PetrolCar":
                            "Ford": [],
                            "Hyundai": []
                            ,
                            "Vehicle":
                            "DieselCar":
                            "Hyundai": []
                            ,
                            "ElectricCar":
                            "Tesla": []
                            ,
                            "PetrolCar":
                            "Ford": [],
                            "Hyundai": []




                            child_names = child_name for toplevel_name, toplevel_children in d.items() for child_name in iter_all_keys(toplevel_children)

                            d = key: value for key, value in d.items() if key not in child_names
                            print(d)


                            Result (whitespace added by me for clarity):




                            'Animal':
                            'Dog':
                            'Labrador':
                            'LabradorPup': []

                            ,
                            'Cat': []
                            ,
                            'Vehicle':
                            'DieselCar':
                            'Hyundai': []
                            ,
                            'PetrolCar':
                            'Hyundai': [],
                            'Ford': []
                            ,
                            'ElectricCar':
                            'Tesla': []





                            Note that this only removes duplicates from the top level. If you were to run this code on a dictionary such as this one:



                            d = 
                            "Human":
                            "Fred": [],
                            "Barney": []
                            ,
                            "Caveman":
                            "Fred": [],
                            "Barney": []




                            ... Then the resulting dict would be identical to the input. Fred and Barney both appear twice in the data structure. If this is not the desired result, it's not clear what the result should be. Should Fred and Barney be removed from Human, or from Caveman? If the logic should be "keep Fred and Barney in Human, because that's the one we encountered first. Get rid of the rest", then the result will not be deterministic, because dictionaries in 2.7 are not guaranteed to be ordered.






                            share|improve this answer















                            I don't think any(child for child in children.values()) is an effective way of determining whether children should stay in the final dict. That expression is basically equivalent to "does this dict have at least one value that isn't an empty string?". The Dog dict has a non-empty child, so it remains in your final dict.



                            Here's the approach I would use. Write a function that recursively iterates over a nested data structure and yields all of its keys, no matter how deeply they are nested. Run this function on every top-level key-value pair to identify the names of all child values. Then create a new dict that excludes those names from the top level.



                            def iter_all_keys(obj):
                            if not isinstance(obj, dict):
                            return
                            for key, value in obj.items():
                            yield key
                            for x in iter_all_keys(value):
                            yield x

                            d =
                            "Animal":
                            "Cat": [],
                            "Dog":
                            "Labrador":
                            "LabradorPup": []


                            ,
                            "DieselCar":
                            "Hyundai": []
                            ,
                            "Dog":
                            "Labrador":
                            "LabradorPup": []

                            ,
                            "ElectricCar":
                            "Tesla": []
                            ,
                            "Labrador":
                            "LabradorPup": []
                            ,
                            "PetrolCar":
                            "Ford": [],
                            "Hyundai": []
                            ,
                            "Vehicle":
                            "DieselCar":
                            "Hyundai": []
                            ,
                            "ElectricCar":
                            "Tesla": []
                            ,
                            "PetrolCar":
                            "Ford": [],
                            "Hyundai": []




                            child_names = child_name for toplevel_name, toplevel_children in d.items() for child_name in iter_all_keys(toplevel_children)

                            d = key: value for key, value in d.items() if key not in child_names
                            print(d)


                            Result (whitespace added by me for clarity):




                            'Animal':
                            'Dog':
                            'Labrador':
                            'LabradorPup': []

                            ,
                            'Cat': []
                            ,
                            'Vehicle':
                            'DieselCar':
                            'Hyundai': []
                            ,
                            'PetrolCar':
                            'Hyundai': [],
                            'Ford': []
                            ,
                            'ElectricCar':
                            'Tesla': []





                            Note that this only removes duplicates from the top level. If you were to run this code on a dictionary such as this one:



                            d = 
                            "Human":
                            "Fred": [],
                            "Barney": []
                            ,
                            "Caveman":
                            "Fred": [],
                            "Barney": []




                            ... Then the resulting dict would be identical to the input. Fred and Barney both appear twice in the data structure. If this is not the desired result, it's not clear what the result should be. Should Fred and Barney be removed from Human, or from Caveman? If the logic should be "keep Fred and Barney in Human, because that's the one we encountered first. Get rid of the rest", then the result will not be deterministic, because dictionaries in 2.7 are not guaranteed to be ordered.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Mar 26 at 14:34

























                            answered Mar 26 at 14:27









                            KevinKevin

                            62.3k11 gold badges77 silver badges121 bronze badges




                            62.3k11 gold badges77 silver badges121 bronze badges





















                                0














                                Try This:



                                I Know its Complicated.



                                aa = [i for i,j in a.items()]
                                bb = [get_all_keys(j) for i,j in a.items()]

                                for i in aa:
                                for j in bb:
                                if i in j:
                                for k in a:
                                if k==i:
                                del a[k]


                                Tell me you are getting right or wrong.






                                share|improve this answer



























                                  0














                                  Try This:



                                  I Know its Complicated.



                                  aa = [i for i,j in a.items()]
                                  bb = [get_all_keys(j) for i,j in a.items()]

                                  for i in aa:
                                  for j in bb:
                                  if i in j:
                                  for k in a:
                                  if k==i:
                                  del a[k]


                                  Tell me you are getting right or wrong.






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    Try This:



                                    I Know its Complicated.



                                    aa = [i for i,j in a.items()]
                                    bb = [get_all_keys(j) for i,j in a.items()]

                                    for i in aa:
                                    for j in bb:
                                    if i in j:
                                    for k in a:
                                    if k==i:
                                    del a[k]


                                    Tell me you are getting right or wrong.






                                    share|improve this answer













                                    Try This:



                                    I Know its Complicated.



                                    aa = [i for i,j in a.items()]
                                    bb = [get_all_keys(j) for i,j in a.items()]

                                    for i in aa:
                                    for j in bb:
                                    if i in j:
                                    for k in a:
                                    if k==i:
                                    del a[k]


                                    Tell me you are getting right or wrong.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 26 at 14:33









                                    Rohit-PandeyRohit-Pandey

                                    1,16810 silver badges18 bronze badges




                                    1,16810 silver badges18 bronze badges



























                                        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%2f55359039%2fremove-keys-from-a-nested-dictionary-if-they-appear-elsewhere-as-a-value%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

                                        Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                        Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                        Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript