如何将字典中以%开头的键对应的值转换为float类型?
解决方法
注意:你的原始字典里存在重复键# scheduled,Python字典中重复键会被最后出现的条目覆盖,因此实际生效的是'# scheduled': 9697。
处理代码
# 整理后的原始字典 route_stats = { 'Month': 'July', '# short': 8, '# cancelled': 6, '% TT delivered': '0.9978408389882788', '% ontime': '0.85284108487160981', '% cancelled': '0.0018507094386181369', '% short': '0.0024676125848241827', '# scheduled': 9697, '# ontime': 8270, 'Route': '82', 'Year': 2005 } # 转换指定键的值类型 for key, val in route_stats.items(): if key.startswith('%'): route_stats[key] = float(val) # 查看转换后的结果 print(route_stats)
代码说明
- 遍历字典所有键值对,用
startswith('%')筛选出以%开头的键 - 对符合条件的值执行
float()类型转换,直接更新字典对应条目 - 非目标键的内容保持原有类型不变
内容的提问来源于stack exchange,提问作者z star
相关产品推荐
相关产品推荐

