首页 > 编程语言 >python 中字典内置函数get()

python 中字典内置函数get()

时间:2022-08-15 14:48:26浏览次数:51  
标签:200 内置 dict1 get python ## 400 字典

 

001、

>>> dict1 = {"a":100, "b":200, "c":300, "d":400, "e":500}          ## 测试字典
>>> dict1
{'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 500}
>>> dict1.get("b")                                                 ## 获取键b的值
200
>>> dict1.get("d")                                                 ## 获取键d的值
400
>>> dict1.get("x")                                                 ## 当不存在该键时,则返回为空
>>> dict1.get("x", "NA")                                           ## 可以设定当不存在该键时, 返回指定的内容
'NA'

 

002、利用字典.get()函数, 可以在字典中检索相应键对应的值的情况

>>> dict1 = {"a":100, "b":200, "c":300, "d":400, "e":500}          ## 测试字典
>>> dict1
{'a': 100, 'b': 200, 'c': 300, 'd': 400, 'e': 500}
>>> idx = "axybd"                                                  ## 可迭代键值
>>> idx
'axybd'
>>> for i in idx:                                                  ## 结合for循环,检索特定键在字典中的情况
...     print(i, dict1.get(i,"no exist"))
...
a 100
x no exist
y no exist
b 200
d 400

 

标签:200,内置,dict1,get,python,##,400,字典
From: https://www.cnblogs.com/liujiaxin2018/p/16588233.html

相关文章