我如何在Python 3中展平嵌套字典?

时间:2014-06-27 09:34:21

标签: python dictionary nested

是否存在将嵌套字典展平为输出字典的本机函数,其中键和值采用以下格式:

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

假设字典有几种不同的值类型,我该如何重复字典?

1 个答案:

答案 0 :(得分:3)

您想要遍历字典,构建当前密钥并累积平面字典。例如:

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, '', {})

使用它:

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

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