美文网首页
python 字典

python 字典

作者: 秋殇灬 | 来源:发表于2018-05-03 10:29 被阅读0次

假设字典为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

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}

相关文章

网友评论

      本文标题:python 字典

      本文链接:https://www.haomeiwen.com/subject/wtlkrftx.html