zoukankan      html  css  js  c++  java
  • python dict get函数

    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'}
    '''
  • 相关阅读:
    01月04日假期学习
    个人加分项
    12月16日总结
    12月15日总结
    12月13日总结
    01月01日假期学习
    01月02日假期学习
    12月14日总结
    12月17日总结
    01月05日假期学习
  • 原文地址:https://www.cnblogs.com/cgmcoding/p/14428632.html
Copyright © 2011-2022 走看看