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

Python字典无法通过整数索引取值的解决方法求助

解决Python字典无法通过整数索引取值的问题

Python 中的字典是键值对映射结构,并非有序序列(Python 3.7 及以上版本才会保留插入顺序,但本质仍不是可索引的序列类型),所以直接用dict[0]这类整数索引取值必然报错。

以下是几种可行的解决方法:

方法1:按插入顺序获取指定位置的值(Python3.7+)

如果你的Python版本是3.7或更高,字典会保留插入顺序,可先把字典的键或值转为列表,再用索引访问:

  • 获取第一个值:
my_dict = {
  'red' : 'purple',
  'blue' : 'orange',
  'green' : 'cyan'
}
# 直接取第一个值
first_value = list(my_dict.values())[0]
print(first_value)  # 输出 'purple'

# 或者先取第一个键,再取值
first_key = list(my_dict.keys())[0]
first_value = my_dict[first_key]

方法2:使用有序数据结构适配索引访问

如果需要频繁通过整数索引操作数据,建议直接改用列表存储,或者使用collections.OrderedDict(兼容Python3.7以下版本的有序字典):

from collections import OrderedDict

ordered_dict = OrderedDict([
    ('red', 'purple'),
    ('blue', 'orange'),
    ('green', 'cyan')
])
# 转为列表后按索引访问
first_value = list(ordered_dict.values())[0]

注意事项

你之前尝试的dict[(.)]、dict(.)等写法都是语法错误,不符合Python的语法规范,请勿使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:09:55