a_h
a_h

Reputation: 41

Convert key:list of strings to key:list of integers in dictionary

I've got a dictionary of key:list pairs. The lists are lists of strings, but they need to be integers. Here is an example of what I'm starting with:

dictionary = {
    "P4021a": ["1","2","3","4","5"],
    "P4019a": ["1","2","3","4","5"],
    "P4013a": ["1","2","3","4","5"]
}

I'm trying to achieve the following:

dictionary = {
    "P4021a": [1,2,3,4,5],
    "P4019a": [1,2,3,4,5],
    "P4013a": [1,2,3,4,5]
}

Here is what I've tried so far:

new_dict = {}
for key in dictionary.keys():
    new_dict[key] = dictionary[int(key)]

I get an error stating the int() cannot operate on a list. So I've also tried to add iteration through each list.

new_dict = {}
for key in dictionary.keys():
    new_dict[key] = dictionary[[int(value) for value in dictionary.values() for i in range(5)]]

I've also tried:

new_dict = {}
for key in dictionary.keys():
    new_dict[key] = dictionary[map(int,key)]

Any help is appreciated.

Upvotes: 2

Views: 1803

Answers (2)

vks
vks

Reputation: 67978

for i in dictionary:
    dictionary[i]=map(int,dictionary[i])
print dictionary

You can simply map to int.

In Python 3 as pointed out by Bhargav, map returns a map object instead of a list hence you need to use

list(map(int,dictionary[i]))

Upvotes: 2

DeepSpace
DeepSpace

Reputation: 81654

for key in dictionary:
    dictionary[key] = [int(val) for val in dictionary[key]]

Upvotes: 0

Related Questions