1 __author__ = 'ZZG' 2 3 #key-value 4 #字典无序,没有下标,通过key来寻找 5 info ={ 6 'cat':'animal', 7 'flower':'plant', 8 'lemon':'fruit'} 9 10 print(info) 11 12 #查找 13 print(info['cat']) 14 print(info.get('cat')) 15 print('cat'in info) 16 17 #更改字典中的值 18 info['lemo']='水果' 19 print(info) 20 21 #创建一个键值对 22 info['book']='none' 23 print(info) 24 25 #删除字典 26 del info['book'] 27 info.pop('cat') 28 info.popitem()#随意删除一个 29 print(info)
#设置默认字典用法
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 info ={ 2 'cat':'animal', 3 'flower':'plant', 4 'lemon':'fruit'} 5 6 info.setdefault("dog",'animal') 7 print(info)
#update的用法
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 a = { 2 'student1':"xiaoming", 3 'student2':'xiaozhang', 4 'student3':'xiaoxi'} 5 b = { 6 'student1':'zhangshuai', 7 'student4':'liuhua', 8 'student5':'jincai', 9 1:2, 10 2:3} 11 a.update(b) 12 print(a)
#items 用法将字典转换为列表
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 a = { 2 'student1':"xiaoming", 3 'student2':'xiaozhang', 4 'student3':'xiaoxi'} 5 6 print(a.items())
#初始化一个新的字典
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 c = dict.fromkeys([1,2,3], "姓名") 2 print(c)
#字典的循环
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 a = { 2 'student1':"xiaoming", 3 'student2':'xiaozhang', 4 'student3':'xiaoxi'} 5 #推荐的循环 6 for i in a: 7 print(i,a[i]) 8 #另一种循环 9 for v,k in a.items(): 10 print(v,k)