Python 字典(Dictionary) get() 函数返回指定键的值。
dict.get(key, default=None)
- key -- 字典中要查找的键。
- default -- 如果指定键的值不存在时,返回该默认值。
- #!/usr/bin/python
dict = {'Name': 'Runoob', 'Age': 27}
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Sex', "Not Available")
如果字典里面嵌套有字典,无法通过 get() 直接获取 value:
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
本文介绍了Python字典的get()方法,用于安全地获取键对应的值,当键不存在时返回默认值。示例展示了如何使用get()获取嵌套字典中的值,以及在键不存在时提供默认值。
781

被折叠的 条评论
为什么被折叠?



