Reputation: 60
I have a dictionary as follows
data = {'CNN': ['5.89', '2.34'], 'BBC': ['6.78', '4.45']}
How do I convert the Strings in value lists into float?
So it becomes
data = {'CNN': [5.89, 2.34], 'BBC': [6.78, 4.45]}
Any help would be appreciated!
Upvotes: 0
Views: 897
Reputation: 3828
The two answers already posted create new dictionaries which, if they really are that small, might be of no consequence.
If, however, the dictionary was very large, a better option may be to simply convert the strings to float in place within the existing dictionary.
data = {'CNN': ['5.89', '2.34'], 'BBC': ['6.78', '4.45']}
for k in data.keys():
for i in range(len(data[k])):
data[k][i] = float(data[k][i])
Output
{'CNN': [5.89, 2.34], 'BBC': [6.78, 4.45]}
Upvotes: 0
Reputation: 5449
Here a solution:
data = {'CNN': ['5.89', '2.34'], 'BBC': ['6.78', '4.45']}
data_float = {}
for k,v in data.items():
data_float[k] = [float(elem) for elem in v]
data_float
Output:
{'BBC': [6.78, 4.45], 'CNN': [5.89, 2.34]}
Upvotes: 0
Reputation: 22776
You can use a dict-comprehension and map
:
data = {k : list(map(float, v)) for k, v in data.items()}
Output:
{'CNN': [5.89, 2.34], 'BBC': [6.78, 4.45]}
Upvotes: 1