python字典
来源:互联网 发布:ubuntu14 cuda8 caffe 编辑:程序博客网 时间:2024/05/01 13:04
字典又称为关联表,是一种由键映射到值的数据结构,具有查找时间是常数的性能
一个字典条目的语法格式是 键:值。 而且,多条字典条目被包含在( { } ) 里。
1.创建字典和给字典赋值
wordcount={"hello":10,"world":32}
多从赋值,同时给多个字典赋值
(wordcount1,wordcount2)=({"hello":10,"world":32},{"world":12})
使用内建方法生成默认字典,以列表或者元组中的元素作为键,以输入的默认值作为每个键的值
wordcount={}.fromkeys(['hello','world'],1)
wordcount={}.fromkeys(('hello','world'),1)
2.访问字典
就和访问列表和元组一样,只不过是使用键作为下标
wordcount['hello']
但是首先要保证键值对在字典里,否则会有一个错误,可以使用'hell' in wordcount测试某个
键值对在不在字典里
遍历所有的字典元素
for key in wordcount:
print key,wordcount[key]
所有字典的键 wordcount.keys(),所有字典的值 wordcount.values(),所有键值对wordcount.items()
3.更新字典的值
和列表一样,下标换为键就可以了
wordcount['hello']=22
4.删除字典里的键值对
del wordcount['hello']#删除hello对应的键值对
wordcount.clear()#删除字典所有的键值对
一个字典条目的语法格式是 键:值。 而且,多条字典条目被包含在( { } ) 里。
1.创建字典和给字典赋值
wordcount={"hello":10,"world":32}
多从赋值,同时给多个字典赋值
(wordcount1,wordcount2)=({"hello":10,"world":32},{"world":12})
使用内建方法生成默认字典,以列表或者元组中的元素作为键,以输入的默认值作为每个键的值
wordcount={}.fromkeys(['hello','world'],1)
wordcount={}.fromkeys(('hello','world'),1)
2.访问字典
就和访问列表和元组一样,只不过是使用键作为下标
wordcount['hello']
但是首先要保证键值对在字典里,否则会有一个错误,可以使用'hell' in wordcount测试某个
键值对在不在字典里
遍历所有的字典元素
for key in wordcount:
print key,wordcount[key]
所有字典的键 wordcount.keys(),所有字典的值 wordcount.values(),所有键值对wordcount.items()
3.更新字典的值
和列表一样,下标换为键就可以了
wordcount['hello']=22
4.删除字典里的键值对
del wordcount['hello']#删除hello对应的键值对
wordcount.clear()#删除字典所有的键值对
- Python 字典
- python 字典
- Python:字典
- Python 字典
- python字典
- Python 字典
- python 字典
- python 字典
- Python 字典
- Python字典
- python 字典
- python字典
- python 字典
- python 字典
- python--字典
- python 字典
- python字典
- Python---字典
- Mysql Innodb 学习经验
- 线性表---学生成绩管理--数据结构课程设计
- JVM内存分配机制
- JavaSE基础:GUI
- Raspberry Pi 搭建 LAMP, Linux, Apache, MySQL, PHP web server
- python字典
- Discuz! X2.5安装模板插件出现:对不起,您安装的不是正版应用,安装程序无法继续执行的解决方法
- jQuery选择器大全
- 喜愛的程式設計名言
- EMACS教程中文版
- Vim进阶攻略
- PacketiX VPN 配置笔记
- Objective-c的Foundation中常用类4——字典NSDictionary、NSMutableDictionary
- 驾驶笔记