拜访字典中的项
能够应用 [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…