python字典key不能是可以是啥类型
作者:FXL 时间:2022-12-28 20:54:04
python中字典的key不能是可变类型。字典可存储任意类型对象,其中值可以取任何数据类型,但键必须是不可变的,如字符串、数字或元组。语法格式:【d = {key1 : value1, key2 : value2}】。
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
代码实现:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
内容扩展:
Python中字典的key都可以是什么?
答:一个对象能不能作为字典的key,就取决于其有没有__hash__方法。所以所有python自带类型中,除了list、dict、set和内部至少带有上述三种类型之一的tuple之外,其余的对象都能当key。
比如数值/字符串/完全不可变的元祖/函数(内建或自定义)/类(内建或自定义)/方法/包等等你能拿出手的,不过有的实际意义不高。还有数值型要注意,因为两个不同的相等数字可以有相同的哈希值,比如1和1.0。
解释:
代码版本:3.6.3;文档版本:3.6.6
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can't use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append()and extend().
字典的键可以是任意不可变类型,需要注意的是tuple元组作为键时,其中不能以任何方式包含可变对象。
来源:https://www.py.cn/jishu/jichu/19683.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于Python实现扑克牌面试题
pytorch 输出中间层特征的实例
Google logo “我的中国”谷歌国际少年绘画大赛小学1-3年级
![](https://img.aspxhome.com/file/UploadPic/200812/19/j1-3_01-72s.jpg)
pyshp创建shp点文件的方法
itchat-python搭建微信机器人(附示例)
基于Python数据结构之递归与回溯搜索
如何将Python字符串转换为JSON的实现方法
Oracle数据库性能优化技术开发者网络Oracle
python logging 日志的级别调整方式
卸载VS2011 Developer Preview后Sql Server2008 R2建立数据库关系图报“找不到指定的模块”错误的解决方法
基于Python实现开心消消乐小游戏的示例代码
![](https://img.aspxhome.com/file/2023/8/86428_0s.jpg)
python编写猜数字小游戏
![](https://img.aspxhome.com/file/2023/4/101254_0s.jpg)
Symfony2实现在controller中获取url的方法
python实现xml转json文件的示例代码
Django框架使用富文本编辑器Uedit的方法分析
五分钟学会Python 模块和包、文件
![](https://img.aspxhome.com/file/2023/8/79488_0s.png)
Selenium多窗口切换解决方案
![](https://img.aspxhome.com/file/2023/3/95683_0s.png)
Python Django框架单元测试之文件上传测试示例
![](https://img.aspxhome.com/file/2023/0/75920_0s.png)
python爬虫爬取微博评论案例详解
![](https://img.aspxhome.com/file/2023/7/92497_0s.png)