onehamed
onehamed

Reputation: 127

convert Element of list value in Dictionary Python

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?

Upvotes: 1

Views: 73

Answers (4)

Mohammad Bajalal
Mohammad Bajalal

Reputation: 107

a similar question asked already check that too! you can do this also:

arr = [{
    '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'],
    }]

[{k : list(map(float, v))  for k, v in point.items() } for point in arr]

Upvotes: 1

justjokingbro
justjokingbro

Reputation: 167

array=[{'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']}]
new_array=array[0]

for i in new_array.values():
    k=0
    for j in i:
        i[k]=int(float(j))
        k=k+1
        
print(new_array)

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

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]}]

Upvotes: 1

user7864386
user7864386

Reputation:

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]}]

Upvotes: 2

Related Questions