如何拼合嵌套词典? [英] How to flatten a nested dictionary?

查看:117
本文介绍了如何拼合嵌套词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您想遍历字典,构建当前键并累积平面字典.例如:

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

使用它:

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

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

这篇关于如何拼合嵌套词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆