我在创建字典时尝试保存数据类型。
以下示例始终将所有变量存储为字符串:
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}
如何自动创建具有正确类型的字典?
答案 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}