2

访问字典中的项

可以使用 [key] 的方式来访问字典中的项,比如获取下面字典中的 key=model 的值,代码如下:


thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
x = thisdict["model"]
print(x)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
Mustang

当然除了中括号,还可以使用 get() 方法来访问,如下代码所示:


x = thisdict.get("model")

获取字典中的所有 keys

要想获取字典中的所有 keys,可以直接调用 dict 的 keys() 方法即可。


thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
keys = thisdict.keys()
print(keys)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
dict_keys(['brand', 'model', 'year'])

获取字典中的所有 values

除了可以获取 dict 中的 keys,还可以通过 values() 获取 dict 中的所有value,如下代码所示:


thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
keys = thisdict.values()

print(keys)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
dict_values(['Ford', 'Mustang', 1964])

获取字典中的每一项

上面的方法分别从 dict 中获取 keys 或者 values,这一节我们调用 items() 获取字典中的 key-value 集合,如下代码所示:


thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

items= thisdict.items()

print(items)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

检查字典中是否存在指定key

要想判断字典中是否存在某一个 key,可以用 python 内置的 in 操作符即可,如下代码所示:


thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
Yes, 'model' is one of the keys in the thisdict dictionary
译文链接:https://www.w3schools.com/pyt...

一线码农
366 声望1.6k 粉丝