python中字典取值的两种方法

方法一:dic.get('key', 默认值) 

dic1 = {'1':'node1','2':'node2'}
print(dic1.get('1')) # node1
print(dic1.get('3', 'no such key')) # no such key 若字典中没有该键,则返回默认值

若字典中没有该键,则返回默认值。

 方法二:使用方括号[]

dic1 = {'1':'node1','2':'node2'}
print(dic1['1']) # node1
print(dic1['3']) # KeyError: '3'

使用方括号[],dic['key']时要求key必须在dic中存在,否则报错。

 

 建议使用方法一:dic.get('key', 默认值) 来获取字典中的键值对。因为当键不存在时不会报错,会用默认值填充。