十进制列表到字典中的浮动列表

时间:2018-10-24 14:52:39

标签: python list dictionary

我从mssql查询中获得了包含小数的列表。如:

 [(1, Decimal('33.00'), Decimal('5.30'), Decimal('50.00')),
  (2, Decimal('17.00'), Decimal('0.50'), Decimal('10.00'))]

我想像这样将其转换为字典和浮点数:

 {1: [33.00, 5.30, 50.00],
  2: [17.00, 0.50, 10.00]}

我写在下面一行:

load_dict = {key: values for key, *values in dataRead}

结果:

{1: [Decimal('33.00'), Decimal('105.30'), Decimal('25650.00')],
 2: [Decimal('17.00'), Decimal('40.50'), Decimal('10000.00')]}

我想问的是,是否有这种通过列表/字典理解进行转换的方法?

2 个答案:

答案 0 :(得分:3)

您可以像这样将dict-comprehension与强制转换为float

from decimal import Decimal

lst = [(1, Decimal('33.00'), Decimal('5.30'), Decimal('50.00')),
  (2, Decimal('17.00'), Decimal('0.50'), Decimal('10.00'))]

ret = {key: [float(f) for f in values] for key, *values in lst}
print(ret)
# {1: [33.0, 5.3, 50.0], 2: [17.0, 0.5, 10.0]}

答案 1 :(得分:1)

float应用于值:

from decimal import Decimal

data = [(1, Decimal('33.00'), Decimal('5.30'), Decimal('50.00')),
  (2, Decimal('17.00'), Decimal('0.50'), Decimal('10.00'))]

load_dict = {key: list(map(float, values))  for key, *values in data}

print(load_dict)

输出

{1: [33.0, 5.3, 50.0], 2: [17.0, 0.5, 10.0]}