Reputation: 542
I have been trying to look at other questions and not found anything that works for me. I have a list if dictionaries (trips) and want to access the values in each dictionary within the list of trips, and convert if from a string to a float.
If i take trips[0] output is:
# {'pickup_latitude': '40.64499',
# 'pickup_longitude': '-73.78115',
# 'trip_distance': '18.38'}
I am trying to build a function that iterates through the list of dictionaries, accessing the values and transferring them to floats.
I have tried various versions of the code below, including trying to build a new dictionary and returning that
def float_values(trips):
for trip in trips:
for key, value in trip.items():
value = float(value)
return
float_values[0] should output:
# {'pickup_latitude': 40.64499,
# 'pickup_longitude': -73.78115,
# 'trip_distance': 18.38}
Continuously getting
'function' object is not subscriptable'
OR
'NoneType' object is not subscriptable
Upvotes: 2
Views: 409
Reputation: 452
If you what to override your values from the dictionary you should do something like this
def float_values(trips):
for trip in trips:
for key, value in trip.items():
trip[key] = float(value)
return trips
By doing value = float(value)
you are writing temporary the float value and not saving it anywhere
Upvotes: 2
Reputation: 2392
Simply what you need to do is change value inside the dictionary:
for list_dict in list_of_dicts:
for key, value in list_dict.items():
list_dict[key] = float(value)
Upvotes: 1