Convert dictionary values to floats based on key

Question:

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

Asked By: z star

||

Answers:

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)
Answered By: Unmitigated
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.