Python中字典的Get()方法

Python get()方法 如果字典中存在给定键,则返回该键的值。如果不是,那么它将返回None(如果get()只与一个参数一起使用)。

null

语法: Dict.get(key,默认值=None)

参数:

  • 关键: 要从中返回值的项的键名
  • 价值: (可选)未找到密钥时返回的值。默认值为“无”。

返回: 返回具有指定键的项的值。

Python Dictionary get()方法示例

示例1:Python get()方法适用于字典

python

dic = { "A" : 1 , "B" : 2 }
print (dic.get( "A" ))
print (dic.get( "C" ))
print (dic.get( "C" , "Not Found ! " ))


输出:

1NoneNot Found !

示例2:Python Dictionary get()方法嵌套

get()在没有值的情况下进行检查和分配,以完成此特定任务。如果没有任何密钥,只返回非错误None。

Python3

# Python3 code to demonstrate working of
# Safe access nested dictionary key
# Using nested get()
# initializing dictionary
test_dict = { 'Gfg' : { 'is' : 'best' }}
# printing original dictionary
print ( "The original dictionary is : " + str (test_dict))
# using nested get()
# Safe access nested dictionary key
res = test_dict.get( 'Gfg' , {}).get( 'is' )
# printing result
print ( "The nested safely accessed value is :  " + str (res))


输出:

The original dictionary is : {'Gfg': {'is': 'best'}}The nested safely accessed value is :  best

本文由 马扬克·拉瓦特 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享