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

Python嵌套字典循环缩进问题及TypeError报错求助

问题分析:TypeError: int与str无法相加

问题描述

我正在学习《Python编程快速上手:让繁琐工作自动化(第2版)》,尝试在for循环后添加缩进插入num_brought值时,持续报错:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

书本参考代码

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
             'Bob': {'ham sandwiches': 3, 'apples': 2},
             'Carol': {'cups': 3, 'apple pies': 1}}

def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():
        numBrought = numBrought + v.get(item, 0)
    return numBrought
    
print('Number of things being brought:')
print(' - Apples         ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups           ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes          ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies     ' + str(totalBrought(allGuests, 'apple pies')))

我的代码

all_guests = {
    'Alice': {'apple': 1, 'ham': 2},
    'Joe': {'potato': 7, 'beer': 7},
    'Carl': {'apple': 3, 'beer': 'none'}}

def total_brought(guest, item):
    num_brought = 0
    for k, v in guest.items():
        num_brought = num_brought + v.get(item, 0)
    return num_brought

print('Total brought: ')
print('Apples: ' + str(total_brought(all_guests, 'apple')))
print('Beer: ' + str(total_brought(all_guests, 'beer')))
print('Ham: ' + str(total_brought(all_guests, 'ham')))
print('Potato: ' + str(total_brought(all_guests, 'potato')))

问题根源

报错和缩进无关,核心是字典内数据类型不统一:

  • 你的all_guests中,Carl的beer值是字符串'none',但其他用户的beer是整数7
  • 函数计算总数时,会尝试把整数7和字符串'none'相加,Python不允许整数与字符串直接执行加法操作,因此抛出TypeError

修复方案

方案1:统一字典数据类型(推荐)

将Carl的beer值改为整数0,代表未携带该物品:

all_guests = {
    'Alice': {'apple': 1, 'ham': 2},
    'Joe': {'potato': 7, 'beer': 7},
    'Carl': {'apple': 3, 'beer': 0}  # 替换'none'为0
}

方案2:在函数中兼容类型转换

如果需要保留字符串形式的“无”,可以在函数里添加类型判断与转换逻辑:

def total_brought(guest, item):
    num_brought = 0
    for k, v in guest.items():
        value = v.get(item, 0)
        # 尝试将字符串转为整数,转换失败则按0处理
        if isinstance(value, str):
            try:
                value = int(value)
            except ValueError:
                value = 0
        num_brought += value
    return num_brought

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:17:07