How would I flatten a nested dictionary in Python 3? [duplicate]

对着背影说爱祢 提交于 2019-12-13 10:03:09

问题


Is there a native function to flatten a nested dictionary to an output dictionary where keys and values are in this format:

_dict2 = {
  'this.is.an.example': 2,
  'this.is.another.value': 4,
  'this.example.too': 3,
  'example': 'fish'
}

Assuming the dictionary will have several different value types, how should I go about iterating the dictionary?


回答1:


You want to traverse the dictionary, building the current key and accumulating the flat dictionary. For example:

def flatten(current, key, result):
    if isinstance(current, dict):
        for k in current:
            new_key = "{0}.{1}".format(key, k) if len(key) > 0 else k
            flatten(current[k], new_key, result)
    else:
        result[key] = current
    return result

result = flatten(my_dict, '', {})

Using it:

print(flatten(_dict1, '', {}))

{'this.example.too': 3, 'example': 'fish', 'this.is.another.value': 4, 'this.is.an.example': 2}


来源:https://stackoverflow.com/questions/24448543/how-would-i-flatten-a-nested-dictionary-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!