python基础语法——字典中的dict.get(key)与dict[key]

字典中的dict.get(key)会返回指定键key的值。
基本使用方法:

dict.get(key)

返回值:如果字典中的key不存在,会返回None或者默认值。

具体使用实例:

if __name__ == '__main__':
    run = {
        "i": {
            "title": "交互式编程( Interactive )",
            "desc": [
                "打开终端,输入 python 回车",
                "进入 Python 交互式命令行",
                "输入 print('monkey king is coding!')"
            ]
        },
        "f": {
            "title": "Python 源代源文件( File )",
            "desc": [
                "使用你喜欢的编辑器拷贝本练习的代码, 保存为run.py",
                "打开终端,cd 到 run.py 保存的目录",
                "输入 python run.py"
            ]
        }
    }

    print("有两种基本的方式运行 Python")
    for s in run:
        print('s',s) #s为字典的键
        item = run.get(s) #字典中的get为获取字典的指定键的值  iterm又属于一个字典,再次获取其键值
        print("* {}: {}".format(s, item['title']))

    has_learn_i = False
    has_learn_f = False

    # TODO(You): 请在此实现代码

    if has_learn_i and has_learn_f:
        print("[2/2]您已完成两种 Python 运行方式的学习")
    elif has_learn_f:
        print("[1/2]您已完成 Python 源代码方式运行学习")
    elif has_learn_i:
        print("[1/2]您已完成 Python 交互式命令行运行学习")
    else:
        print("[0/2]您似乎跳过了运行方式的学习?期待下次光临!")
        
     

dict.get(key)与dict[key]的区别之处。

  • dict.get()当key在字典中无法找到时,会返回None或者默认值。、
  • dict[key]:当key在字典中找不到时,会触发异常:KeyError异常。
  • 示例:
>>> runoob = {}
>>> print('URL: ', runoob.get('url'))     # 返回 None
URL:  None

>>> print(runoob['url'])     # 触发 KeyError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'url'
>>>
  • get在嵌套字典中的使用:
  • 使用多个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

版权声明:本文为qq_38978225原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。