Python Dictionary get()方法教程

Python字典数据类型提供 get() 方法以返回字典中的指定项。由于字典项由键值对组成,因此通常使用键返回值。

null

Dictionary get()方法语法

dictionary get()方法具有以下语法。

DICT.get(KEY,VALUE)
  • 口述 get()方法将运行的字典。
  • 钥匙 是我们寻找其价值的关键。get()方法需要该键。
  • 如果找不到指定的密钥,则提供 价值 将被退回。VALUE参数是可选的。

Dictionary get()方法示例

为了理解dictionary数据类型的get()方法,让我们做一些示例。首先,我们将创建一个名为fruits的字典,其中items包含水果名称作为键,counts作为值。

fruits = { "apple":12 , "banana":5 , "tomato":7 }count = fruits.get("apple")print(count)count = fruits.get("tomato")print(count)
图片[1]-Python Dictionary get()方法教程-yiteyi-C++库

现在举例说明指定的键在给定的字典中不存在。我们将提供VALUE参数,如果指定的键不存在,它将被返回。对于这个场景,我们将查找不存在的水果,因为它不存在,所以0将作为值返回。

fruits = { "apple":12 , "banana":5 , "tomato":7 }count = fruits.get("grape")print(count)count = fruits.get("grape",0)print(count)
图片[2]-Python Dictionary get()方法教程-yiteyi-C++库

我们还可以对嵌套字典使用get()方法,其中字典中的项也是字典。也可以是不同的数据类型,但在本例中,我们将以嵌套字典为例。

fruits = { "apple":{ "color":"red" , "count":12} , "banana":5 , "tomato":7 }apple= fruits.get("apple")color = apple.get("color")count = apple.get("count")print(color)print(count)
图片[3]-Python Dictionary get()方法教程-yiteyi-C++库

在本例中,首先我们将得到“apple”项值,它也是dictionary,包含“color”和“count”键。然后我们得到“color”和“count”值。

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