[英]How can I convert nested dictionary keys to strings?
original
dictionary keys are all integers. original
字典键都是整数。 How can I convert all the integer keys to strings using a shorter approach? 如何使用较短的方法将所有整数键转换为字符串?
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
prints: 印刷品:
{'1': {}, '2': {'202': 'TwoZeroTwo', '101': 'OneZeroOne'}}
Depending on what types of data you have: 根据您拥有的数据类型:
original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
result= json.loads(json.dumps(original))
print(result)
prints: 印刷品:
{'2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}, '1': {}}
If you don't know the number of levels, then a recursive solution is probably best: 如果您不知道级别数,那么最好使用递归解决方案:
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
if you know that all values are either dicts or simple values, then you can remove all the elifs and the convert_list
function 如果您知道所有值都是字典或简单值,则可以删除所有省略号和
convert_list
函数
def f(d):
new = {}
for k,v in d.items():
if isinstance(v, dict):
v = f(v)
new[str(k)] = v
return new
import json
original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
text = json.dumps(original)
json.loads(text)
out: 出:
{'1': {}, '2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.