转换键:字符串列表为键:字典中的整数列表

时间:2015-08-29 19:46:54

标签: python dictionary

我有一个关键字词典:列表对。列表是字符串列表,但它们必须是整数。这是我开始的一个例子:

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

我正在努力实现以下目标:

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

这是我到目前为止所尝试的内容:

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

我收到错误,指出int()无法在列表上运行。所以我也尝试在每个列表中添加迭代。

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

我也试过了:

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

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

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

您可以mapint

在{3}}指出的Python 3中,map会返回map object而不是list因此您需要使用

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

答案 1 :(得分:0)

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