Python - 访问字典项
访问字典项
您可以通过引用方括号内的键名来访问字典中的项:
实例
获取"model"键的值:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
亲自试一试 »
还有一个名为 get() 的方法,也能得到相同的结果:
获取键
`keys() 方法将返回字典中所有键的列表。
键列表是字典的视图,这意味着对字典所做的任何更改都会反映在键列表中。
实例
向原始字典添加一个新项,并查看键列表是否也随之更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] =
"white"
print(x) #after the change
亲自试一试 »
获取值
`values()` 方法将返回字典中所有值的列表。
值列表是字典的视图,这意味着对字典所做的任何更改都会反映在值列表中。
实例
修改原始字典,看看值列表是否也随之更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"]
= 2020
print(x) #after the change
亲自试一试 »
实例
向原始字典中添加一个新项,并查看值列表是否也随之更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"]
= "red"
print(x) #after the change
亲自试一试 »
获取项
`items() 方法会将字典中的每个项以元组的形式返回到一个列表中。
返回的列表是字典项的视图,这意味着对字典所做的任何更改都会反映在项列表中。
实例
对原始字典进行更改,并查看项列表是否也随之更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["year"]
= 2020
print(x) #after the change
亲自试一试 »
实例
向原始词典添加一个新条目,并查看条目列表是否也随之更新:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x) #before the change
car["color"]
= "red"
print(x) #after the change
亲自试一试 »
检查键是否存在
要确定指定的键是否存在于字典中,请使用 in 关键字:
实例
检查字典中是否存在"model":
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is
one of the keys in the thisdict dictionary")
亲自试一试 »

