python 字典的KeyError处理方法
先看一段代码:
user = dict(name="brainliao", age=32)
print(user["sex"])
运行结果如下:
user这个字典中没有sex这个key,所以访问user[“sex”]会报KeyError这个错
有如下3中解决方式:
1、调用get(k, default)方法
user = dict(name="brainliao", age=32)
print(user.get("sex", "男"))
结果如下:
男
2、用collections.defaultdict()方法
import collections
user = collections.defaultdict(str)
print(user["sex"])
结果打印出空字符串
这个方法的含义在于指定了字典中的所有values均为字符串,并默认值为空字符串。所有调用user["sex"]不会报错。但是这种方法有局限性,就是不适合不同的key对应不用类型的value的字典定义。
3、重定义__missing__方法
class User(dict): def __missing__(self,key):
print("调用了 User的__missing__方法")
return "__missing__" def __getitem__(self, item):
print("调用User 类的 __getitem__方法")
return super(User, self).__getitem__(item) def get(self, k, d=None):
print("调用User 类的 get 方法")
return super(User, self).get(k, d) user = User(name="brianliao", age=32)
print(user["sex"])
打印结果如下:
调用User 类的 __getitem__方法
调用了 User的__missing__方法
__missing__
从打印的结果可以看出,获取字典key对应的值时,会去调用内部的__getitem__方法,而当__getitem__没找到对应的key时,会调用__missing__方法。最终返回结果。
总结,最简单、最直接的方式还是使用第一种方式,第二种方式具有很大的局限性,第三种方式在一些特殊情况下很合适使用。
python 字典的KeyError处理方法的更多相关文章
- python字典改变value值方法总结
今天这篇文章中我们来了解一下python之中的字典,在这文章之中我会对python字典修改进行说明,以及举例说明如何修改python字典内的值.我们开始进入文章吧. 首先我们得知道什么是修改字典 修改 ...
- python字典对象的update()方法
使用字典对象的update()方法,如A.update(B),将B字典的键值对一次性全部添加到A字典对象,当A字典为空时,相当于深复制,非常方便.如果两个字典中存在相同的键,则进行值的更新. A={} ...
- python 字典的定义以及方法
7.字典的转换: dict(x=1,y=2) ==> {'y': 2, 'x': 1} dict([(i,element) for i, element in enumerate(['one ...
- python 字典中的get()方法
https://blog.csdn.net/weixin_38705903/article/details/79231551
- Python 字典方法
访问字典的值 字典中的 键/值 实际上就是一种映射关系,只要知道了 “键”,就肯定知道 “值”. >>> my_dict = dict(name = 'zhangsan',other ...
- Python 字典 popitem() 方法
描述 Python 字典 popitem() 方法随机返回并删除字典中的一个键/值对(一般删除末尾对). 如果字典已经为空,却调用了此方法,就报出KeyError异常. 语法 popitem() 方法 ...
- python之字典二 内置方法总结
Python字典包含了以下内置方法: clear()函数用于删除字典内所有元素 dict1 = {, 'Class': 'First'} print('the start len %d' % len( ...
- python字典copy()方法
python 字典的copy()方法表面看就是深copy啊,明显独立 d = {'a':1, 'b':2} c = d.copy() print('d=%s c=%s' % (d, c)) Code1 ...
- Python 字典(Dictionary) get()方法
描述 Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值. 语法 get()方法语法: dict.get(key, default=None) 参数 ...
随机推荐
- HDU 5552 Bus Routes(2015合肥现场赛A,计数,分治NTT)
题意 给定n个点,任意两点之间可以不连边也可以连边.如果连边的话可以染上m种颜色. 求最后形成的图,是一个带环连通图的方案数. 首先答案是n个点的图减去n个点能形成的树. n个点能形成的树的方案数比 ...
- 洛谷—— P1598 垂直柱状图
P1598 垂直柱状图 题目描述 写一个程序从输入文件中去读取四行大写字母(全都是大写的,每行不超过72个字符),然后用柱状图输出每个字符在输入文件中出现的次数.严格地按照输出样例来安排你的输出格式. ...
- 2017 Hackatari Codeathon B. 2Trees(深搜)(想法)
B. 2Trees time limit per test 0.75 seconds memory limit per test 256 megabytes input standard input ...
- TIANKENG’s restaurant HDU - 4883 (暴力)
TIANKENG manages a restaurant after graduating from ZCMU, and tens of thousands of customers come to ...
- java 抽象方法 能用 静态 static 修饰,或者 native 修饰 么
韩梦飞沙 韩亚飞 313134555@qq.com yue31313 han_meng_fei_sha static与abstract不能同时使用 用static声明方法表明这个方法在不生成类 ...
- 【BZOJ 4104】【THUSC 2015】解密运算
http://www.lydsy.com/JudgeOnline/problem.php?id=4104 网上题解满天飞,我也懒得写了 #include<cstdio> #include& ...
- Bomb Enemy -- LeetCode
Given a 2D grid, each cell is either a wall 'W', an enemy 'E' or empty '0' (the number zero), return ...
- CodeForces - 1000D Yet Another Problem On a Subsequence
题面在这里! 好智障的一个dp啊,一段开头的数字相当于下面要跟多少个数,直接滚动数组dp就行了... #include<bits/stdc++.h> #define ll long lon ...
- POJ ???? Monkey King
题目描述 Once in a forest, there lived N aggressive monkeys. At the beginning, they each does things i ...
- BZOJ 3571 [Hnoi2014]画框(最小乘积完美匹配)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3571 [题目大意] 给出一张二分图,每条边上有a,b两个值,求完美匹配, 使得suma ...