📜  Python中字典的Get()方法

📅  最后修改于: 2022-05-13 01:55:31.569000             🧑  作者: Mango

Python中字典的Get()方法

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

Python字典 get() 方法示例

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

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


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))


输出:

1
None
Not Found !

示例 2:嵌套的Python字典 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