网站首页 > 知识剖析 正文
访问字典中的项
可以使用 [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/python/python_dictionaries_access.asp
猜你喜欢
- 2025-05-25 应该早点了解 Python 中的 5 件事
- 2025-05-25 如何在Python中按值对字典进行排序?
- 2025-05-25 Python多进程:释放多核CPU的洪荒之力
- 2025-05-25 一天快速入门 Python
- 2025-05-25 python零基础不要错过,python字典的所有类型
- 2025-05-25 Python 100个函数及代码!码住
- 2025-05-25 Python速查表
- 2025-05-25 必知必会的15个Python知识点
- 2025-05-25 Python函数参数和返回值类型:让你的代码更清晰、更健壮
- 2025-05-25 Python语言的12个基础知识点小结
- 05-25应该早点了解 Python 中的 5 件事
- 05-25如何在Python中按值对字典进行排序?
- 05-25Python多进程:释放多核CPU的洪荒之力
- 05-25一天快速入门 Python
- 05-25python零基础不要错过,python字典的所有类型
- 05-25Python 100个函数及代码!码住
- 05-25Python速查表
- 05-25必知必会的15个Python知识点
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)