Skip to content Skip to sidebar Skip to footer

Converting Dictionary Values In Python From Str To Int In Nested Dictionary

I currently have a nested dictionary which looks like this: series = { 'a': {'foo':'2', 'bar':'3', 'baz':'7', 'qux':'1'}, 'b': {'foo':'6', 'bar':'4', 'baz':'3', 'qux':'0'}, 'c':

Solution 1:

You have to go deeper in this case:

In [4]: {k: {kk: int(vv) forkk, vv in v.items()}
         fork, v in series.items()}
Out[4]: 
{'a': {'bar': 3, 'baz': 7, 'foo': 2, 'qux': 1},
 'b': {'bar': 4, 'baz': 3, 'foo': 6, 'qux': 0},
 'c': {'bar': 5, 'baz': 1, 'foo': 4, 'qux': 6}}

Your own example just iterates the key, value -pairs of series, which has (nested) dict values.

Note that this is not a generic solution. For that you'd need recursion or a stack.

Solution 2:

int(v) -- v is a dictionary!

this line here, you are trying to convert a dictionary to an integer.

you'll need to nest another dictionary comprehension inside

basically if you replace [int(v)] with something like

[dict((a,int(b) for (a,b) in v.items())]

didn't test that out but you get the idea, also nesting that might get a little messy

i suggest just writing a function that takes a dictionary and converts it's values from strings to int and then you can just replace [int(v)] with something like

 [convertDictValsToInts(v)]

Solution 3:

In your example v is the internal dictionary, not the internal values. What you want to do is turn all values in the internal dict into an int.

{k1: {k2: int(v2) for k2, v2 in series[k1].items()} for k1 in series}

Solution 4:

As stated by Ilja Everilä, if you want a generic solution for all kinds of nested dict, you can use a recursive function.

I guess something like the following would work (will test it when I have some more time).

defseries_to_int(series):
    for k,v in series.items():
        iftype(v) == dict:
            series_to_int(v)
        eliftype(v) == str:
            series[k] = int(v)

Note that the above routine will changes your series in-place. If you want a more functional approach (with a return value that you can use like int_series = series_to_int(series), you'll have to tweak it a little.

Post a Comment for "Converting Dictionary Values In Python From Str To Int In Nested Dictionary"