-2

I'm currently setting up a dictionary and am attempting to convert the values associated with a key from strings to integers. So I'm trying to go from this:

    {'Georgia': ['18', '13', '8', '14']}

To this:

    {'Georgia': [18, 13, 8, 14]}

Any ideas on how I would go about doing this?

Friz_96
  • 13
  • 2
  • 3
    Did you try to look this up at all? http://stackoverflow.com/q/379906/2615940 http://stackoverflow.com/q/4291236/2615940 – skrrgwasme Apr 09 '16 at 22:24

2 Answers2

1

You can do this:

map is taking the values from the iterable in this case the value of the dictionaries key and casting every item in the iterable to an int. map returns a map object instead of a list so we are converting it back to a list.

a_dict = {'Georgia': ['18', '13', '8', '14']}
a_dict['Georgia'] = list(map(int, a_dict['Georgia']))

Or, if you need to convert multiple values this way you can use a loop:

 for k,v in list(a_dict.items()):
     a_dict[k] = list(map(int, v))
Pythonista
  • 11,377
  • 2
  • 31
  • 50
1
>>> old =  {'Georgia': ['18', '13', '8', '14']}
>>> new = {key: list(map(int, value)) for key, value in old.items()}
>>> new
{'Georgia': [18, 13, 8, 14]}
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485