Python读写字典,如果Key不在Dict里面,就会导致抛出KeyError,如果没有做异常处理,那么程序就会挂断,平时自己写来玩耍的程序,挂掉没事,改了再重新跑呗。但是,如果在公司,可能一个程序要跑几天,因为这种小bug挂掉,就要重新跑一遍,非常影响工作效率。所以,读字典时,一定要考虑到Key not in Dict里面的情况,可以选择做异常处理。

 temp = {'a':1,'b':1,'c':1}
 h = ['a','e','c','b']
 for index in h:
      print temp[index]

运行结果:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print temp[index]
KeyError: 'e'

可以选择做异常处理:

 temp = {'a':1,'b':1,'c':1}
 h = ['a','e','c','b']
 for index in h:
      try:
           print temp[index]
      except KeyError:
           print "has no key"

    


运行结果:

1
has no key
1
1

当然异常处理太麻烦了,可以用get函数来读取字典

dict.get(key, default=None)
参数

key -- 这是要搜索在字典中的键。

default -- 这是要返回键不存在的的情况下默认值。

返回值

该方法返回一个给定键的值。如果键不可用,则返回默认值为None。

Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。


dict.setdefault(key, default=None)
参数

  • key -- 查找的键值。
  • default -- 键不存在时,设置的默认键值。

以下实例展示了 setdefault()函数的使用方法:

dict = {'Name': 'Zara', 'Age': 7}

print "Value : %s" %  dict.setdefault('Age', None)
print "Value : %s" %  dict.setdefault('Sex', None)

Value : 7
Value : None


girls =['alice','bernice','clarice']
letterGirls ={}

 for girl in girls:
     letterGirls.setdefault(girl[0],[]).append(girl)
 
 print letterGirls

{'a': ['alice'], 'c': ['clarice'], 'b': ['bernice']}

总结:get是读取时,防止key不存在产生的异常,setdefault是写入时,防止key不存在时产生的异常

更多推荐

Python 读Dict数据的方法,解决key 不在dict的问题,get()函数,setdefault()函数