download:极客工夫-Go进阶训练营|全新降级第4期
假设字典为dics = {0:'a', 1:'b', 'c':3}
1.从字典中取值,当键不存在时不想处理异样
[方法] dics.get('key', 'not found')
[例如]
image
[解释] 当键'key'不存在是,打印'not found'(即想要处理的信息),当存在是输入键值。
【其余解决打算一】
if key in dics:
print dics[key]
else:
print 'not found!!'
【其余解决打算二】
try:
print dics[key]
except KeyError:
print 'not found'
例子:
image
2.从字典中取值,若找到则删除;当键不存在时不想处理异样
[方法] dics.pop('key', 'not found')
[例如]
image
[解释] 当键'key'不存在是,打印'not found'(即想要处理的信息),当存在是输入键值,并且去除该健。
3.给字典增加一个条目。如果不存在,就指定特定的值;若存在,就算了。
[方法] dic.setdefault(key, default)
[例如]
image
- 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}