python中怎样向字典中添加值_如何向字典Python中添加值

不能对字符串执行列表操作:>>> 'string'.append('addition')

Traceback (most recent call last):

File "", line 1, in

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

如果支持添加,则只能向数据结构中添加某些内容:>>> li=['string']

>>> li.append('addition')

>>> li

['string', 'addition']

您要获取由与另一个字符串关联的字符串组成的dict:dictio = {"Object": "Computer"}

把它当作一个列表添加进去。与上述问题相同:>>> dictio["Object"].append("Mouse")

Traceback (most recent call last):

File "", line 1, in

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

怎么办?如果dict中的对象是一个字符串,则它需要是一个列表才能附加到它。

您可以先测试:>>> if isinstance(dictio["Object"], list):

... dictio["Object"].append('Mouse')

... else:

... dictio["Object"]=[dictio["Object"]]

... dictio["Object"].append('Mouse')

...

>>> dictio

{'Object': ['Computer', 'Mouse']}

或者试着去面对失败:try:

dictio["Object"].append("Mouse")

except AttributeError:

dictio["Object"]=[dictio["Object"]]

dictio["Object"].append("Mouse")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值