1

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 dimensionsto a string, like this:

exampleDict['dimensions'] = str(dict['dimensions'])

This works just fine. But imagine there are nested dicts inside my exampleDict, and dimensionsis 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 yieldin 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, nestingand price. The isinstanceis not working properly (or it is and I am not fully understanding its methodology).

Dmitriy Kisil
  • 2,858
  • 2
  • 16
  • 35
M.K
  • 1,464
  • 2
  • 24
  • 46
  • Why not just something like `d[k] = str(d[k])`? Show your desired output, because at the moment your description is confusing. – meowgoesthedog Apr 01 '19 at 15:46
  • Sure, I will edit the question right away. But not like this because I can receive a dict from parameter. It can have `coordinates` in a plain dict, or it can be nested. So I do not know what dict I get! Only that I need to change that! @meowgoesthedog – M.K Apr 01 '19 at 15:49
  • Well to deal with nesting you should call `changeToStringDim` recursively if `isinstance(d[k], dict) == True`, just as the code is doing with `list`. – meowgoesthedog Apr 01 '19 at 15:52
  • Yes, but it is not working. Changing `dict`will cause an error in `string indeces must be integers`in `isinstance(d[k], dict)` @meowgoesthedog – M.K Apr 01 '19 at 16:13
  • The isinstance needs to take a type, be it `list`, `dict`, etc. I am not overriding anything! It needs to take a type! @meowgoesthedog – M.K Apr 01 '19 at 16:19
  • You probably misunderstood my comment and changed the wrong piece of code. I'll upload a solution. – meowgoesthedog Apr 01 '19 at 16:22

1 Answers1

1

Code with comments:

def changeNestedListToString(d):
    for k in d:

        # recursive call on dictionary type
        if isinstance(d[k], dict):
            changeNestedListToString(d[k])

        # convert lists to string
        elif isinstance(d[k], list):
            d[k] = str(d[k])

        # leave everything else untouched

Test data:

example = {
    'name': 'example1',
    'nesting': {
        'subnesting1': 'sub2',
        'coordinates': [41.6769705, 2.288154]
    },
    'price': 123123132
}

After calling the function:

{
    'price': 123123132, 
    'name': 'example1', 
    'nesting': {
         'coordinates': '[41.6769705, 2.288154]', 
         'subnesting1': 'sub2'
    }
}

As you can see 'coordinates' has been converted to a string while everything else was left untouched.

meowgoesthedog
  • 14,670
  • 4
  • 27
  • 40
  • How is coordinates being changed, and not anything else, if in the function, the worth `'coordinates'`does not appear! It is working though! – M.K Apr 01 '19 at 16:35
  • 1
    @M.K it just converts all values of type `list` to strings. If you only want specific keys to be changed you should pass a list of said keys. – meowgoesthedog Apr 01 '19 at 16:36
  • That is even better than what I wanted actually. All types of list to strings is perfect! Thank you! – M.K Apr 01 '19 at 16:39