1.kyes()

(1)取出字典的key

In [32]: myCat
Out[32]: {'colr': 'gray', 'size': 'fat'} In [33]: for i in myCat.keys():
...: print(i)
...:
size
colr

(2)检查字典中是否存在键或值

2.values()

(1)取出字典的value

In [39]: for i in myCat.values():
...: print(i)
...:
fat
gray

3.items()

(1)取出字典的key和value

In [50]: for i in myCat.items():
...: print(i)
...:
('size', 'fat')
('colr', 'gray')

(2)多重赋值

In [58]: myCat
Out[58]: {'colr': 'gray', 'size': 'fat'} In [59]: for k,v in myCat.items():
...: print("key: " + k + " values: "+ v)
...:
key: size values: fat
key: colr values: gray

4.类型转化

(1)通过ist(),生成列表

In [61]: myCat
Out[61]: {'colr': 'gray', 'size': 'fat'} In [62]: myCatlist = list(myCat.keys()) In [63]: myCatlist
Out[63]: ['size', 'colr']

5.get()方法

(1)get()方法有两个参数:要取得其值的键;以及如果该键不存在时,返回的备用值。

6.setdefault()方法

为字典中的键设置默认值,当该键没有任何值时使用它。

setdefault()方法提供了一种方式,在一行中完成这件事。传递给该方法的第一 个参数,是要检查的键。第二个参数,是如果该键不存在时要设置的值。如果该键 确实存在,方法就会返回键的值。

7.删除key

(1)del
删除字典中某组键值对

In [64]: myCat
Out[64]: {'colr': 'gray', 'size': 'fat'} In [65]: del myCat['colr'] In [66]: myCat
Out[66]: {'size': 'fat'}

(2)clear()

清空字典

In [67]: myCat
Out[67]: {'size': 'fat'} In [68]: myCat.clear() In [69]: myCat
Out[69]: {}

(3)pop()

删除字典中某组键值对,并返回值

In [78]: myCat
Out[78]: {'colr': 'gray', 'size': 'fat'} In [79]: myCat.pop('colr')
Out[79]: 'gray' In [80]: myCat
Out[80]: {'size': 'fat'}

(4)pop.item()

随机删除一个键值对

In [82]: myCat = {'colr': 'gray', 'size': 'fat',}

In [83]: myCat.popitem()
Out[83]: ('size', 'fat')

练习

characterCount.py计算message中每个字符出现的次数

#!/usr/bin/env python
#coding:utf-8
from pprint import * message = 'It is bright cold day in April, and the clocks where the striking thirteen.'
count = {} #字典 for character in message:
count.setdefault(character,0) #character=key,value默认=0
count[character] = count[character] + 1 #为key设置value,value=value+1 pprint(count)  #pprint能够对key排序

最新文章

  1. WordPress主题模板层次和常用模板函数
  2. 查看LINUX当前负载
  3. 【液晶模块系列基础视频】5.3.X-GUI字体驱动3
  4. LOL(英雄联盟)系统鼠标速度锁定工具
  5. Python开发过程中17个坑
  6. session相关----高手请跳过!
  7. 用curl自动登录HTTPS站点
  8. c++学习笔记之封装篇(上)
  9. 鼠标悬停,图片放大 CSS实现
  10. python flask 基础入门
  11. 复仇者联盟3热映,我用python爬取影评告诉你它都在讲什么
  12. Python之路(第三十七篇)并发编程:进程、multiprocess模块、创建进程方式、join()、守护进程
  13. 洛谷 P1110 [ZJOI2007]报表统计 解题报告
  14. fastjson 在 springboot中的运用
  15. YAML Class ID Reference
  16. this.class.getClassLoader().getResourceAsStream与this.class.getResourceAsStream 文件地址获取
  17. 项目打包 TestFlight用法
  18. 【面试总结】网易2019秋招一站式面试总结(等offer中……)
  19. Load sharepoint envirement by powershell
  20. android 编译模块

热门文章

  1. pandas 的axis参数的理解
  2. NOIP2016 D2T2 蚯蚓
  3. ES6 Module(模块)
  4. lvm磁盘扩展
  5. c++ printf和cout的性能
  6. 命令——tree
  7. VS2015编译问题:模块对于 SAFESEH 映像是不安全的
  8. BZOJ 2097: [Usaco2010 Dec]Exercise 奶牛健美操 二分 + 贪心 + 树上问题
  9. ZeroMQ的进阶
  10. 解决报错(Could not create connection to database server.)