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

Question:

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)
Asked By: Robain

||

Answers:

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}
Answered By: Alex Montano
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.