创建字典时保存数据类型

时间:2017-06-12 13:20:50

标签: python django python-3.x

我在创建字典时尝试保存数据类型。

以下示例始终将所有变量存储为字符串:

arr = {}
for value in self.method_list[method]:
    try:
        arr[value] = urllib.parse.unquote(request.GET[value])
    except KeyError:
    pass

结果:{'sign': '123'}

我需要将数值数据存储为int:

arr[value] = int(urllib.parse.unquote(request.GET[value]))

结果:{'sign': 123}

如何自动创建具有正确类型的字典?

3 个答案:

答案 0 :(得分:0)

arr = {}
for value in self.method_list[method]:
    try:

        arr[value] = {"value": urllib.parse.unquote(request.GET[value]),
                      "type": type(urllib.parse.unquote(request.GET[value]))

    except KeyError:
        pass

答案 1 :(得分:0)

if urllib.parse.unquote(request.GET[value]).isdigit():
    arr[value] = int(urllib.parse.unquote(request.GET[value]))
else:
    arr[value] = urllib.parse.unquote(request.GET[value])

答案 2 :(得分:0)

以下代码会将数值转换为Python int对象:

from __future__ import print_function

keys = [ 'key1', 'key2', 'key3' ]
vals = [ 123, '456', 'number' ]

arr = dict()

for i in range(len(keys)):
    try:
        arr[keys[i]] = int(vals[i])
    except ValueError:
        arr[keys[i]] = vals[i]

print(arr)

给出:

{'key3': 'number', 'key2': 456, 'key1': 123}