python 字典操作
来源:互联网 发布:360网络监测 编辑:程序博客网 时间:2024/06/02 13:25
假设字典为dics = {0:'a', 1:'b', 'c':3}
1.从字典中取值,当键不存在时不想处理异常
[方法] dics.get('key', 'not found')
[例如]
[解释] 当键'key'不存在是,打印'not found'(即想要处理的信息),当存在是输出键值。
【其他解决方案一】
if key in dics: print dics[key] else: print 'not found!!'
【其他解决方案二】
try: print dics[key] except KeyError: print 'not found'
例子:
2.从字典中取值,若找到则删除;当键不存在时不想处理异常
[方法] dics.pop('key', 'not found')
[例如]
[解释] 当键'key'不存在是,打印'not found'(即想要处理的信息),当存在是输出键值,并且去除该健。
3.给字典添加一个条目。如果不存在,就指定特定的值;若存在,就算了。
[方法] dic.setdefault(key, default)
[例如]
4. update
>>> a = {'a':1, 'b':2}>>> a.update({'c':3})>>> a{'a': 1, 'c': 3, 'b': 2}>>> a.update({'c':4})>>> a{'a': 1, 'c': 4, 'b': 2}
0 0
- Python的字典操作
- Python的字典操作
- python 字典操作备忘
- python 字典操作
- python字典操作
- python中字典操作
- python的{}字典操作
- Python的字典操作
- Python的字典操作
- python 字典操作
- Python的字典操作
- Python的字典操作
- python之字典操作
- Python的字典操作
- Python字典操作
- python 字典/集合操作
- python 字典操作
- Python的字典操作
- 求最大公约数的高效率算法
- 拥抱SVG:苦恼于图片适配 in Android?
- UniqueService
- Python学习路线(针对具备一定编程经验者)
- json的一些demo
- python 字典操作
- GDT,LDT,GDTR,LDTR详解
- LCD1602的使用
- Python——字典
- Javascript中apply、call、bind比较
- Python3:网络爬虫(1)
- 遍历python字典几种方法
- 基础知识之PDO预处理
- 树链剖分学习