The list is ['Australia, 529\n', 'Jamaica, 466\n', 'England, 450\n', 'New Zealand, 391\n', 'South Africa, 363']
How do I convert only the numbers to floats?
CodePudding user response:
You can convert the numbers like this:
result = []
for item in input_list:
country, number = item.split(',')
float_number = float(number.rstrip('\n'))
updated_element = f"{country}, {float_number}\n"
result.append(updated_element)
print(result)
For your input list this will output:
['Australia, 529.0\n', 'Jamaica, 466.0\n', 'England, 450.0\n', 'New Zealand, 391.0\n', 'South Africa, 363.0\n']
To form a dictionary you can do this:
result_dict = {}
for item in input_list:
country, number = item.split(',')
float_number = float(number.rstrip('\n'))
updated_element_dict = {country: float_number}
result_dict.update(updated_element_dict)
print(result_dict)
Above code will output:
{'Australia': 529.0, 'Jamaica': 466.0, 'England': 450.0, 'New Zealand': 391.0, 'South Africa': 363.0}