Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return keys from nested dictionary Python

I have a nested dictionary as such:

{'needed1': {'notneeded': {'needed2': 'some_value'},
  'notneeded2': {'needed2': 'some_value'},
  'notneeded3': {'needed3: 'some_value', 'needed4': 'some_value'},
  'notneeded4': {'needed3': 'some_value', 'needed4': 'some_value'}}}

In which I wrote a function as such:

def get_field_names(category):
    field_names = []
    for info_cat, cat_type in category.items():
        # first key -> needed
        field_names.append(info_cat) 
        for category_type, conditions in cat_type.items():
            # second key -> not needed
            for field in conditions.keys():
                # third key -> needed
                if field not in field_names:
                    field_names.append(field)
                    
    return field_names 

In which the key in the top of the dict and the key within the nest dict (3rd) level are needed. This returns a unique list (in order of nesting) the keys that I need from levels 1 and 3. This code works, but I don’t know how or if there is a more elegant way to write this. I want to understand moreso of the approach to handle this kind of a case to explicitly handle the level of nesting within a to extract keys/values of my choosing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This can help you get your desired output,

def recursive_items(dictionary):
  for key, value in dictionary.items():
    yield (key)
    if type(value) is dict:
      yield from recursive_items(value)
    else:
      yield (key)

keys = set(map(lambda key:key if ("not" not in key) else None, recursive_items(data)))
keys.remove(None)

I took the help of @DmitryTorba’s answer for this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading