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'}}
答案 0 :(得分:3)
取决于您拥有的数据类型:
original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
result= json.loads(json.dumps(original))
print(result)
打印:
{'2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}, '1': {}}
答案 1 :(得分:2)
如果你不知道级别的数量,那么递归解决方案可能是最好的:
def convert_dict(d):
return {str(k): convert_value(v) for k,v in d.items()}
def convert_list(lst):
return [convert_value(item) for item in lst]
def convert_value(v):
if isinstance(v, dict):
return convert_dict(v)
elif isinstance(v, list):
return convert_list(v)
# more elifs..
else:
return v
如果您知道所有值都是dicts或简单值,那么您可以删除所有elif和convert_list
函数
答案 2 :(得分:2)
def f(d):
new = {}
for k,v in d.items():
if isinstance(v, dict):
v = f(v)
new[str(k)] = v
return new
答案 3 :(得分:2)
import json
original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
text = json.dumps(original)
json.loads(text)
出:
{'1': {}, '2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}}