'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



Solution 1:[1]

This can help you get your desired output,

def get_all_keys(mydict):
  for key, value in mydict.items():
    yield key
    if type(value) == dict:
      yield from get_all_keys(mydict[key])

keys = set(map(lambda key:key if ("not" not in key) else None, get_all_keys(data))) - {None}

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1