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

如何创建以元组作为键的Python字典?

如何创建以元组作为键的字典?

元组是可哈希的不可变类型,完全可以直接作为Python字典的键,下面是几种常用的实现方式:

  • 直接初始化字典时定义元组键
# 一次性创建包含多个元组键的字典
fruit_prices = {('apple', 'red'): 5.99, ('banana', 'yellow'): 3.49}
  • 先创建空字典,再逐个添加元组键的条目
student_scores = {}
# 直接通过下标赋值添加元组键
student_scores[('Alice', 'Math')] = 92
student_scores[('Bob', 'English')] = 87
  • 使用update()方法批量添加(对应你给出的示例写法,注意要把value替换成实际的元组键)
product_stock = {}
target_key = ('laptop', '15-inch')
# 用update添加单个元组键条目
product_stock.update({target_key: 45})
# 也可以批量添加多个
product_stock.update({('phone', 'pro'): 120, ('tablet', 'mini'): 78})

需要注意:作为字典键的元组,内部不能包含列表、字典这类可变类型,否则会触发TypeError,比如([1,2], 'test')这种元组就不能作为键,因为列表是不可哈希的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:15:13