Home > other >  how to flat given dictionary in python?
how to flat given dictionary in python?

Time:10-08

below is my code:

from collections.abc import Mapping

my_dict = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}

def parse_dict(in_dict): 
    if isinstance(in_dict, Mapping):
        for k_outer, v_outer in in_dict.items():
            if isinstance(v_outer, Mapping):
                for k_inner, v_inner in v_outer.items():
                    print(v_outer)
            else:
                print({k_outer: v_outer})

parse_dict(my_dict)

expected output : {'abc': 'abc', 'ghi': 'ghi', 'jkl': 'jkl'}

CodePudding user response:

You could recursively flatten the dictionary:

def parse_dict(in_dict, out_dict):
    for k, v in in_dict.items():
        if isinstance(v, dict):
            return parse_dict(v, out_dict)
        else:
            out_dict[k] = v
    return out_dict

print(parse_dict(my_dict, {}))

{'abc': 'abc', 'ghi': 'ghi', 'jkl': 'jkl'}

CodePudding user response:

Another solution, using generators:

my_dict = {"abc": "abc", "def": {"ghi": "ghi", "jkl": "jkl"}}


def flatten_dict(d):
    for k, v in d.items():
        if isinstance(v, dict):
            yield from flatten_dict(v)
        else:
            yield k, v


print(dict(flatten_dict(my_dict)))

Prints:

{"abc": "abc", "ghi": "ghi", "jkl": "jkl"}
  • Related