【问题标题】:AttributeError: 'float' object has no attribute 'append' when trying to append values to existing keyAttributeError:“float”对象在尝试将值附加到现有键时没有属性“append”
【发布时间】:2020-12-12 20:29:12
【问题描述】:

尝试将浮点值附加到 defaultdic 类型字典中的相同键。

from collection import defaultdict

new_dict= defaultdict(list)

for row in list_dict:
    acct=row[acct]
    time_spent= float(row[time_spent])

    if (acct not in new_dict):
        new_dict[acct] = time_spent
    else:
        new_dict[acct].append(time_spent)

给我错误:

AttributeError: 'float' object has no attribute 'append'

如果我删除浮动,

time_spent= float(row[time_spent])

给我,

AttributeError: 'str' object has no attribute 'append'

我必须稍后将这些 time_spent 添加到值列表中,所以我希望它们是浮动的。

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    acct 不在new_dict 中时,您为新键分配一个浮点值(time_spent)。由于您使用的是defaultdict,它会在第一次读取密钥时自动创建一个空的list,因此您应该删除检查,并且无条件地append 新值:

    time_spent= float(row[time_spent])
    new_dict[acct].append(time_spent)
    

    【讨论】:

      猜你喜欢
      • 2018-09-01
      • 2013-11-05
      • 2019-12-31
      • 2021-03-11
      • 2019-03-31
      • 2018-03-17
      • 2018-08-03
      • 2017-07-02
      • 2016-04-15
      相关资源
      最近更新 更多