Home > database >  How do i get rid of the degree sign from my integer when i want to convert it from a string in a dic
How do i get rid of the degree sign from my integer when i want to convert it from a string in a dic

Time:11-01

I have a dictionary as follows:

Measurments = {'Kitchen': '22°', 'Master bedroom': '19°', 'Sitting room': '21°', 'Toilet': '24°', 'Guest bedroom': '18°', 'Garage': '15°', 'Outside': '12°'}

and want to save it in a new dictionary as follows:

newDictionary = {'Kitchen': 22, 'Master bedroom': 19, 'Sitting room': 21, 'Toilet': 24, 'Guest bedroom': 18, 'Garage': 15, 'Outside': 12}




i have tried :
newDictionary = {str(k):int(v) for k,v in measurements.items()}

but it gave me this error code:

ValueError: invalid literal for int() with base 10: '22°'

How do i get rid of the degree sign so i can get the values as integers?

CodePudding user response:

If you are sure if everything has a degree, you can simply do as below.

measurements = {'Kitchen': '22°', 'Master bedroom': '19°', 'Sitting room': '21°', 'Toilet': '24°', 'Guest bedroom': '18°', 'Garage': '15°', 'Outside': '12°'}

newDictionary = {str(k):int(v[:-1]) for k,v in measurements.items()}

print(newDictionary)

CodePudding user response:

try something like this:

newDictionary = {key:int(value.replace('°', '')) for key,value in Measurments.items()}

since your values are all strings now, you can use replace method to remove the °, and then it will be able to convert it to int

CodePudding user response:

You can do it as follow by removing the unwanted character before converting it to int

newDictionary = {str(k):int(v[:-1]) for k,v in measurements.items()}
  • Related