gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:43:13 24 4
gpt4 key购买 nike

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

打印:

{'1': {}, '2': {'202': 'TwoZeroTwo', '101': 'OneZeroOne'}}

最佳答案

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

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

打印:

{'2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}, '1': {}}

关于python - 如何将嵌套的字典键转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41843604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com