Python字典减法报错:TypeError: 不支持dict与float执行减法运算
Fixing the
duration_in_mins Function and TypeError Issue Let’s break down exactly what’s going wrong here and fix it step by step:
The Root Cause of the TypeError
The error TypeError: unsupported operand type(s) for -: 'dict' and 'float' pops up because your current duration_in_mins function returns a dictionary of durations for all three cities—but your assertion expects a single numeric value (the duration for the specific city you pass into the function).
On top of that, your function ignores the datum parameter entirely (it hardcodes references to example_trips instead), which means it would never work with any trip data beyond that fixed example set.
How to Fix the Function
We need to adjust the logic to:
- Use the
datumparameter (the single trip data passed in) instead of hardcoding global example data. - Branch logic based on the input
cityto handle different duration fields and units. - Return a single numeric value (not a dictionary) to match what the assertion expects.
Corrected Code
def duration_in_mins(datum, city): """ Takes as input a dictionary containing info about a single trip (datum) and its origin city (city) and returns the trip duration in units of minutes. Remember that Washington is in terms of milliseconds while Chicago and NYC are in terms of seconds. """ if city in ['NYC', 'Chicago']: # Convert seconds (from 'tripduration' field) to minutes duration_seconds = float(datum['tripduration']) return round(duration_seconds / 60, 4) elif city == 'Washington': # Convert milliseconds (from 'Duration (ms)' field) to minutes duration_ms = float(datum['Duration (ms)']) return round(duration_ms / 60000, 4) else: # Catch invalid city inputs to avoid silent failures raise ValueError(f"Unsupported city: {city}") # Test cases tests = {'NYC': 13.9833, 'Chicago': 15.4333, 'Washington': 7.1231} # Run assertion tests for city in tests: assert abs(duration_in_mins(example_trips[city], city) - tests[city]) < .001 print("All tests passed successfully!")
Key Improvements in the Corrected Code
- Uses the input
datum: Pulls the duration value directly from the trip data passed into the function, making it reusable for any trip entry. - City-specific logic: Handles the different field names and unit conversions correctly:
- NYC/Chicago: Converts seconds (from
tripduration) to minutes by dividing by 60. - Washington: Converts milliseconds (from
Duration (ms)) to minutes by dividing by 60000 (since 1 minute = 60 * 1000 milliseconds).
- NYC/Chicago: Converts seconds (from
- Returns a single value: The function now outputs a float, which matches what the assertion is trying to compare.
- Error handling: Adds a
ValueErrorfor unexpected city inputs to catch mistakes early.
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

