Home > Software engineering >  convert Element of list value in Dictionary Python
convert Element of list value in Dictionary Python

Time:03-06

I have a data like that

[{'point1': ['20.900', '15.300', '20.400'], 
  'point2': ['0.600', '34.700', '8.100'], 
  'point3': ['12.100', '15.800', '2.300'], 
  'point4': ['15.000', '5.800', '16.900']}]

How can I convert the numbers into integers?

CodePudding user response:

You could use a loop:

for d in lst:
    for v in d.values():
        for i, num in enumerate(v):
            v[i] = int(float(num))

print(lst)

Output:

[{'point1': [20, 15, 20],
  'point2': [0, 34, 8],
  'point3': [12, 15, 2],
  'point4': [15, 5, 16]}]

CodePudding user response:

Try this in one line:

l = [{'point1': ['20.900', '15.300', '20.400'], 'point2': ['0.600', '34.700', '8.100'], 'point3': ['12.100', '15.800', '2.300'], 'point4': ['15.000', '5.800', '16.900']}]

result = [{k: [int(float(i)) for i in v] for k, v in l[0].items()}]

The result will be:

[{'point1': [20, 15, 20],
  'point2': [0, 34, 8],
  'point3': [12, 15, 2],
  'point4': [15, 5, 16]}]
  • Related