关于python词典(Dictionary)的get()用法

先贴出参考链接:http://www.runoob.com/python/att-dictionary-get.html

get()方法语法:

dict.get(key, default=None)

1. 先定义字典

>>>dict = {'A':1, 'B':2}

2. 当key值存在于dict.keys()中时,调用get()方法,返回的是对应的value值

>>>print(dict.get('A'))

返回为:

1

3. 当key值不存在于dict.keys()中时,调用get()方法,返回的是None

>>>print(dict.get('C'))

返回为:

None

4. 当default = x时,若key值存在于dict.keys()时,返回dict[key];若不存在于dict.keys()中时,返回x

>>>print(dict.get('A', 0))
>>>1
>>>print(dict.get('C', 0))
>>>0

注意:dict.get(key,0)可用于计数,并将键值保存在词典中。

原文地址:https://www.cnblogs.com/lliuye/p/8629389.html