如何将嵌套字典的所有值转换为字符串? [英] How to convert all values of a nested dictionary into strings?

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

问题描述

我正在编写一个python应用程序,其中有一个可嵌套到任何级别的可变字典.

I am writing a python application where I have a variable dictionary that can be nested upto any level.

任何级别的键都可以是int或string.但是我想将所有级别的所有键和值都转换为字符串.字典的嵌套方式是可变的,这使它有点复杂.

The keys in any level can be either int or string. But I want to convert all keys and values at all levels into strings. How nested the dictionary will be is variable which makes it a bit complicated.

{
    "col1": {
        "0": 0,
        "1": 8,
        "2": {
            0: 2,
        }
        "3": 4,
        "4": 5
    },
    "col2": {
        "0": "na",
        "1": 1,
        "2": "na",
        "3": "na",
        "4": "na"
    },
    "col3": {
        "0": 1,
        "1": 3,
        "2": 3,
        "3": 6,
        "4": 3
    },
    "col4": {
        "0": 5,
        "1": "na",
        "2": "9",
        "3": 9,
        "4": "na"
    }
}

我正在寻找实现这一目标的最短,最快的功能.还有其他问题,例如转换字典值在python中从str到int在嵌套字典中的int 提出了解决方法,但是它们都没有处理字典的可变嵌套"性质.

I am looking for the shortest and quickest function to achieve that. There are other questions like Converting dictionary values in python from str to int in nested dictionary that suggest ways of doing it but none of them deals with the "variable nesting" nature of the dictionary.

任何想法都会受到赞赏.

Any ideas will be appreciated.

推荐答案

这是我想到的最简单的方法:

This is the most straightforward way I can think of doing it:

import json

data = {'col4': {'1': 'na', '0': 5, '3': 9, '2': '9', '4': 'na'}, 'col2': {'1': 1, '0': 'na', '3': 'na', '2': 'na', '4': 'na'}, 'col3': {'1': 3, '0': 1, '3': 6, '2': 3, '4': 3}, 'col1': {'1': 8, '0': 0, '3': 4, '2': {0: 2}, '4': 5}}
stringified_dict = json.loads(json.dumps(data), parse_int=str)

以下是指向json加载和parse_int文档的链接: Python3 Python2

Here are some links to the documentation for json loads and parse_int: Python3, Python2

这篇关于如何将嵌套字典的所有值转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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