Search code examples
pythondictionarynested

Extract a simple one from a nested dictionary and sort out elements based on a condition


The following dictionary is given:

dict_nested = {"A":{"C":100, "D":{"E":100, "F":100}}, "B":200}

The result should look like this:

dict_result = {"C":100, "E":100, "F":100, "B":200}
  • the result should be 1 Dictionary which only contain the key-value pairs, which its values are from type Integer and not dict.
  • the order should be maintained (i dont mean the alphabetical order of the keys)

Solution

  • Like Sembei said, recursion is needed for this case:

    dict_nested = {"A":{"C":100, "D":{"E":100, "F":100}}, "B":200}
    
    def extract_dict(d1, d2):
        for k, v in d1.items():
            if isinstance(v, dict):
                extract_dict(v, d2)
            elif isinstance(v, int):
                d2.update({k: v})
    
    dict_result = {}
    extract_dict(dict_nested, dict_result)
    print(dict_result)
    

    Output:

    {'C': 100, 'E': 100, 'F': 100, 'B': 200}