2

I have list from mssql query which includes Decimals. Such as:

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

I want to transform that to dict and float number like that:

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

I writed below line:

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

which results:

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

I am asking that is there anyway making this transformation with list/dict comprehension?

kur ag
  • 591
  • 8
  • 19

2 Answers2

3

you could use a dict-comprehension with a cast to float like this:

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]}
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

Apply float to values:

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)

Output

{1: [33.0, 5.3, 50.0], 2: [17.0, 0.5, 10.0]}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76