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...
相关文章
相关标签/搜索