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 的 dict 类中的 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'))

它将产生以下输出-

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

实施例4

与“[]”运算符不同,如果未找到键,get() 方法不会引发错误;它返回无。

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