假设字典为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}
网友评论