cgmcoding

 

Python 字典(Dictionary) get() 函数返回指定键key的值value

dict.get(key, default=None)
  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值。

返回指定键的值,如果键不在字典中返回默认值 None 或者设置的默认值。

dict = {\'Name\': \'Runoob\', \'Age\': 27}

print ("Value : %s" %  dict.get(\'Age\'))
print ("Value : %s" %  dict.get(\'Sex\', "Not Available"))
\'\'\'
Value : 27
Value : Not Available
\'\'\'

 

如果字典里面嵌套有字典,无法通过 get() 直接获取 value,意思说要经过层层获取,而不是一下子get,最内层就会出来

dict_test = {\'Name\': \'Runoob\', \'num\':{\'first_num\': \'66\', \'second_num\': \'70\'}, \'age\': \'15\'}

print(dict_test.get(\'first_num\')) # None
print(\'{:^50}\'.format(\'*\'*50))
print(dict_test.get(\'num\').get(\'first_num\')) # 66
print(dict_test.get(\'num\'))
\'\'\'
None
**************************************************
66
{\'first_num\': \'66\', \'second_num\': \'70\'}
\'\'\'

 

分类:

技术点:

相关文章: