Python字典以及常见的操作
字典
字典可以理解为列表的升级版
列表
list={“dandan”,"zhangsan","wangwu"}
字典
dic={'name':'淡淡','sex':'男','professional':'计算机科学与技术'}
如果需要修改"zhangsan",则需要先找到它的下标,而字典是根据名字找(相当于html中的id),下标没有id好记
- 字典和列表一样可以存取多个数据。
- 列表查询元素通过下标,字典查询元素通过:前面那个值,例如上面代码中的'name','sex'
- 字典中每个元素由两部分组成前面为id后面为值
字典常见操作
与列表类似
打印字典中的元素
print(dic['name'])
修改
- 通过id找到
- 赋值
temp=raw_input("请输入修改后的值") dic['name']=temp print("修改后的值为%s"%dic['name'])
添加
如果给一个字典中不存在的id赋值,则字典中会增加这个元素vqq=raw_input("请输入QQ号") dic['qq']=vqq print("添加后的QQ号为%s"%dic['qq'])
![1240](http://upload-images.jianshu.io/upload_images/3858429-90861f64cec027c0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
image.png
删除
- del
- 删除指定元素
- 删除整个字典(删除之后不能访问)
- clear()
- 清空整个字典,删除之后可以访问
![1240](http://upload-images.jianshu.io/upload_images/3858429-5ae7345992935068.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
删除指定元素
![1240](http://upload-images.jianshu.io/upload_images/3858429-69a2988cf3066456.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
del删除整个字典
![1240](http://upload-images.jianshu.io/upload_images/3858429-c45a56cd8fbd27b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
清空字典
len()查字典中元素个数
一个元素即一个ID和一个值
![1240](http://upload-images.jianshu.io/upload_images/3858429-bf7fc23a1cb14ca1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
查元素个数
keys
![1240](http://upload-images.jianshu.io/upload_images/3858429-a9918694850f4de2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
查看包含字典所有key的列表
values
![1240](http://upload-images.jianshu.io/upload_images/3858429-ee43536b7c74c2c9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
查看包含所有值的列表
items
![1240](http://upload-images.jianshu.io/upload_images/3858429-3494ba534bb8ac4b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
将字典中的元素以列表形式显示出来
has_key
dic.has_key('key')如果key在字典中,返回True,如果不存在返回False
![1240](http://upload-images.jianshu.io/upload_images/3858429-9c1744ab381c312a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
has_key
遍历字典中的元素(与for循环遍历列表类似)
遍历字典中所有的key
![1240](http://upload-images.jianshu.io/upload_images/3858429-255527ac42f072d8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
image.png
遍历字典中所有的value
![1240](http://upload-images.jianshu.io/upload_images/3858429-e0c638c755e63926.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
image.png
遍历字典中所有的items
![1240](http://upload-images.jianshu.io/upload_images/3858429-3aa9908ba58995a6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
image.png
遍历字典中所有的key-value(键值对)
![1240](http://upload-images.jianshu.io/upload_images/3858429-bb4460d6a6d5a115.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
image.png