Need to modify a value in a dictionary to a float and append dictionary

Hello everyone. I have a value in a dictionary that I need to divide by a float and then append the dictionary to update the value. When I try to do this python says it can’t do this as the number is not a float.

Here is what I have so far:
car = {‘price’: ‘30000’}


Well, in that case don’t make the number as a string object:

car = {'price': 30000}


car = {'price': float('30000')}

Sorry, scrap that: I misunderstood your post.

Try this: car['price'] = float(car.get('price'))

You can then get the price as a floating point number with: price = car.get('price')

@rob42 Excellent, now I have the price variable as a float. I divided by the number I need…now how do I append the original dictionary with the updated value?

Simply use the same kind of method that I used, so…

car['price'] = value

… where value is the new price, based on your calculation.

Excellent, thank you so much!


No worries. There is a more concise way to do that, but as you’re still learning the basics, I didn’t want to confuse you with contracted code.


It is better to use:

car['price'] = float(car['price'])
  1. Easier to understand, more straightforward.
  2. Fails with a more precise exception when the key 'price' does not exist.

The get() method is suitable if you need a default value (the default default :slight_smile: None is not suitable for float()):

car['price'] = float(car.get('price', 0))

Good points, well made.