Marielle Dado
Marielle Dado

Reputation: 147

Converting dictionary values that are lists of strings to lists of integers

I have a dictionary with keys that are lists of strings (which are numbers), something like this:

 mydict = {'green': ['-1', '0'],
 'orange': ['-1', '0', '9'],
 'red': ['-1', '0'],
 'yellow': ['0'],
 'white': ['-1'],
 'black': ['-1'],
 'pink': ['-1']}

Now I'd like to convert the values to integers, such that:

mydict = {'green': [-1, 0],
     'orange': [-1, 0, 9],
     'red': [-1, 0],
     'yellow': [0],
     'white': [-1],
     'black': [-1],
     'pink': [-1]}

I've tried using list comprehension

mydict_int =dict((k,int(v)) for k,v in mydict.items())

but it throws an error:

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

Upvotes: 1

Views: 5184

Answers (4)

Mykola Zotko
Mykola Zotko

Reputation: 17864

You can map int to each element in the list as well:

{k: list(map(int, v)) for k, v in mydict.items()}

Upvotes: 0

new = {}
for i in mydict:
    new[i] = [int(k) for k in mydict[i]]

this is how you can convert the strings into integers. but this code assumes that there won't be any non integer values in the list

Upvotes: 1

jez
jez

Reputation: 15359

You have to not only iterate over dictionary keys (for which, incidentally, the "dict comprehension" syntax is easier to read), but also over each value of the list of each dictionary value:

mydict_int = { k : [int(value) for value in sequence]   for k, sequence in mydict.items() }

The exception you are reporting comes from trying to pass the whole list itself in int() rather than each element.

Upvotes: 1

meowgoesthedog
meowgoesthedog

Reputation: 15035

You cannot directly convert lists to int, but you can individually convert their elements with a list comprehension:

mydict_int = dict((k, [int(s) for s in v]) for k,v in mydict.items())

Upvotes: 4

Related Questions