-2
dict = {0: ['2', '6'], 1: ['2'], 2: ['3']}

print("Original: ")
print(dict)

for key,vals in dict.items():
    vals = [int(s) for s in vals]

print("New: ")
print(dict)

Output:

Original: 
{0: ['2', '6'], 1: ['2'], 2: ['3']}
New: 
{0: ['2', '6'], 1: ['2'], 2: ['3']}

I can't figure why the list of values is not changing, I have tried the map() function and it also does not work, any reason why?

Erik L
  • 3
  • 1

2 Answers2

2

In Python 3:

dict = {k: list(map(int, v)) for k, v in dict.items()}
omikron
  • 2,745
  • 1
  • 25
  • 34
  • In the first row - I suppose it for Python 2 - you have a mistake. You should change it to something like `dict(((k, list(map(int, v))) for k, v in d.items()))` because Python 2 doesn't support dict generator – Andrii Rusanov Mar 01 '16 at 11:19
  • I was thinking about Python 2.7 which has it backported. I remove first row entirely since tags has `python` and most recent version that all should aim to work with is Python 3. – omikron Mar 01 '16 at 14:42
1

Because you don't overwrite actually values in your dictionary. Try to do:

for key,vals in dict.items():
    dict[key] = [int(s) for s in vals]

With dict comprehensions it looks much better, actually. I just tried to show what should be changed in your code.

Andrii Rusanov
  • 4,405
  • 2
  • 34
  • 54