如何将嵌套字典键转换为字符串?

alp*_*ric 5 python json dictionary

original字典键都是整数.如何使用更短的方法将所有整数键转换为字符串?

original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}

result = {}
for key in original:
    if not key in result:
        result[str(key)]={}
    for i, value in original[key].items():
        result[str(key)][str(i)] = value
print result 
Run Code Online (Sandbox Code Playgroud)

打印:

{'1': {}, '2': {'202': 'TwoZeroTwo', '101': 'OneZeroOne'}}
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 3

取决于您拥有的数据类型:

original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
result= json.loads(json.dumps(original))
print(result)
Run Code Online (Sandbox Code Playgroud)

印刷:

{'2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}, '1': {}}
Run Code Online (Sandbox Code Playgroud)