I have the following dictionary:
{'Month': 'July', '# short': 8, '# cancelled': 6, '% TT delivered': '0.9978408389882788', '% ontime': '0.85284108487160981', '% cancelled': '0.0018507094386181369', '% short': '0.0024676125848241827', '# scheduled': 3242, '# scheduled': 9697, '# ontime': 8270, 'Route': '82', 'Year': 2005}
I want to convert all values where the key starts with a % to floats
>Solution :
You can use a dict comprehension:
d = {'Month': 'July', '# short': 8, '# cancelled': 6, '% TT delivered': '0.9978408389882788', '% ontime': '0.85284108487160981', '% cancelled': '0.0018507094386181369', '% short': '0.0024676125848241827', '# scheduled': 3242, '# scheduled': 9697, '# ontime': 8270, 'Route': '82', 'Year': 2005}
res = {k: float(v) if k.startswith('%') else v for k, v in d.items()}
Or, to modify the dict in-place:
for k, v in d.items():
if k.startswith('%'):
d[k] = float(v)