python字典按位置索引或 ‘dict_values‘ object does not support indexing

python字典是无法按照位置索引的,只有寻找键对。
a = {'0.jpg': 'cloudy', '1.jpg': 'cloudy', '2.jpg': 'cloudy', '3.jpg': 'sunny', '4.jpg': 'cloudy',
'5.jpg': 'cloudy', '6.jpg': 'cloudy', 
'7.jpg': 'cloudy', '8.jpg': 'sunny', '9.jpg': 'cloudy', '10.jpg': 'cloudy'} #创建一个字典

type(a)
print(a.keys())  #键
print(a.values())#值

#直接对a.keys()和a.values()索引是行不通的,先把其转换为列表再进行索引
list(a.keys())[1:5]
list(a.values())[1:5]

这样做能实现对字典的定位索引,当然这是方法之一,肯定还有更好的方法!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]中提到,"TypeError: 'dict_keys' object does not support indexing"错误是因为Python 3以后的版本改变了dict.keys的返回值,返回的是dict_keys对象,不支持索引值。\[1\]而引用\[2\]中指出,在Python 3中,dict.values()(以及dict.keys()和dict.items())返回的是一个视图对象,而不是一个列表。为了解决这个问题,可以将返回的对象强制转换为list对象,如引用\[3\]所示。所以,对于你提到的"TypeError: 'Book' object does not support indexing"错误,可能是因为你在尝试对一个Book对象进行索引操作,而Book对象不支持索引。如果你想对一个对象进行索引操作,你需要确保这个对象是一个可索引的类型,比如列表或字符串。 #### 引用[.reference_title] - *1* *3* [解决Python字典出现“TypeError: 'dict_keys' object does not support indexing”错误](https://blog.csdn.net/Sophia_11/article/details/85173558)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [【python】错误TypeError: ‘dict_valuesobject does not support indexing when的改出](https://blog.csdn.net/gongdiwudu/article/details/130312098)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值