Python 入門系列 —— 22. dict 的基本操做詳解

訪問字典中的項

能夠使用 [key] 的方式來訪問字典中的項,好比獲取下面字典中的 key=model 的值,代碼以下:python

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() 方法來訪問,以下代碼所示:markdown

x = thisdict.get("model")

獲取字典中的全部 keys

要想獲取字典中的全部 keys,能夠直接調用 dict 的 keys() 方法便可。app

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,以下代碼所示:this

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 集合,以下代碼所示:code

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 操做符便可,以下代碼所示:get

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...
相關文章
相關標籤/搜索