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