1

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': {'foo':'4', 'bar':'5', 'baz':'1', 'qux':'6'}
}

And I'm trying to convert the values from strings into integers.

I have tried this method:

newseries = dict((k,int(v)) for k,v in series.items())

But all I get is an error message saying:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict'

What am I doing wrong?

Jack Levent
  • 75
  • 1
  • 5

4 Answers4

5

You have to go deeper in this case:

In [4]: {k: {kk: int(vv) for kk, vv in v.items()}
         for k, 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.

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
0

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)]
Koborl
  • 235
  • 1
  • 11
0

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}
numeral
  • 504
  • 4
  • 7
0

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).

def series_to_int(series):
    for k,v in series.items():
        if type(v) == dict:
            series_to_int(v)
        elif type(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.

Jivan
  • 21,522
  • 15
  • 80
  • 131