Python 访问字典项

Python 访问字典项

使用[ ]运算符

在Python中,字典不是一个序列,因为字典中的元素没有索引。但是,您可以使用方括号”[ ]”运算符来获取字典对象中与特定键相关联的值。

示例1

capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Gujarat is : ", capitals['Gujarat'])
print ("Capital of Karnataka is : ", capitals['Karnataka'])

它将会产生以下 输出

Capital of Gujarat is: Gandhinagar
Capital of Karnataka is: Bengaluru

示例2

如果方括号内给定的键不在字典对象中,Python会引发KeyError。

capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Captial of Haryana is : ", capitals['Haryana'])

它将产生以下 输出

print ("Captial of Haryana is : ", capitals['Haryana'])
                                      ~~~~~~~~^^^^^^^^^^^
KeyError: 'Haryana'

使用 get() 方法

Python的字典类中的 get() 方法返回与给定键相关联的值。

语法

Val = dict.get("key")

参数

  • key − 在字典对象中用作键的不可变对象

返回值

get()方法返回与给定键映射的对象。

示例3

capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Gujarat is: ", capitals.get('Gujarat'))
print ("Capital of Karnataka is: ", capitals.get('Karnataka'))

将产生以下输出: output

Capital of Gujarat is: Gandhinagar
Capital of Karnataka is: Bengaluru

示例4

与”[]”运算符不同,get()方法在找不到键时不会引发错误,而是返回None。

capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Haryana is : ", capitals.get('Haryana'))

它将产生以下 输出

Capital of Haryana is : None

示例5

get() 方法接受一个可选的字符串参数。如果传入参数,且键未找到,此字符串将成为返回值。

capitals = {"Maharashtra":"Mumbai", "Gujarat":"Gandhinagar", "Telangana":"Hyderabad", "Karnataka":"Bengaluru"}
print ("Capital of Haryana is : ", capitals.get('Haryana', 'Not found'))

以下是产出结果的示例 输出

Capital of Haryana is: Not found

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程