Reputation: 19379
original
dictionary keys are all integers. 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'}}
Upvotes: 5
Views: 2253
Reputation: 49842
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': {}}
Upvotes: 3
Reputation: 12168
import json
original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
text = json.dumps(original)
json.loads(text)
out:
{'1': {}, '2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}}
Upvotes: 3
Reputation: 23783
def f(d):
new = {}
for k,v in d.items():
if isinstance(v, dict):
v = f(v)
new[str(k)] = v
return new
Upvotes: 3
Reputation: 27361
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
Upvotes: 2