I have a dict like this one:
exampleDict={'name': 'Example1', 'code': 2, 'price': 23, 'dimensions': [2,2]}
And I want to change the type of dimensions
to a string, like this:
exampleDict['dimensions'] = str(dict['dimensions'])
This works just fine. But imagine there are nested dicts inside my exampleDict
, and dimensions
is a bit far inside.
My guess is to do something recursively. From what I have searched in here, (examples like this one, or this one, they use yield
in a recursive function, but I am not sure why it's used.
I was thinking on doing this:
def changeToStringDim(d):
if 'dimensions' in d:
d['dimensiones'] = str(d['dimensions'])
for k in d:
if isinstance(d[k], list):
for i in d[k]:
for j in changeToStringDim(i):
j[dimensions] = str(j['dimensions'])
I found it in here, but instead of the assignment of j[dimensions]=str(j['dimensions'])
it did a yield
.But I adapted the solution to this, and it works fine in a dict like this example.
Now I am trying to do it in a nested one.
exDict2={'name': 'example1',
'nesting': {'subnesting1': 'sub2',
'coordinates': [41.6769705, 2.288154]},
'price': 123123132}
}
With the same function but changing it to coordinates:
def changeToStringCoord(d):
if 'coordinates' in d:
d['coordinates'] = str(d['coordinates'])
for k in d:
if isinstance(d[k], list):
for i in d[k]:
for j in changeToStringDim(i):
j['coordinates'] = str(j['coordinates'])
And it won't do anything. I have debugged it, and it will just go through name
, nesting
and price
. The isinstance
is not working properly (or it is and I am not fully understanding its methodology).