Handle self-references when flattening dictionary
问题 Given some arbitrary dictionary mydict = { 'first': { 'second': { 'third': { 'fourth': 'the end' } } } } I've written a small routine to flatten it in the process of writing an answer to another question. def recursive_flatten(mydict): d = {} for k, v in mydict.items(): if isinstance(v, dict): for k2, v2 in recursive_flatten(v).items(): d[k + '.' + k2] = v2 else: d[k] = v return d It works, giving me what I want: new_dict = recursive_flatten(mydict) print(new_dict) {'first.second.third.fourth