You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Use the datum parameter (the single trip data passed in) instead of hardcoding global example data.
  2. Branch logic based on the input city to handle different duration fields and units.
  3. 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).
  • Returns a single value: The function now outputs a float, which matches what the assertion is trying to compare.
  • Error handling: Adds a ValueError for unexpected city inputs to catch mistakes early.

内容的提问来源于stack exchange,提问作者Joseph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:57:29