龙空技术网

Python 入门系列——22. dict 操作详解

一线码农聊技术 47

前言:

而今各位老铁们对“python判断dict”可能比较珍视,大家都需要剖析一些“python判断dict”的相关知识。那么小编也在网摘上汇集了一些有关“python判断dict””的相关资讯,希望姐妹们能喜欢,朋友们快快来了解一下吧!

访问字典中的项

可以使用 [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.pyMustang

当然除了中括号,还可以使用 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.pydict_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.pydict_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.pydict_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.pyYes, 'model' is one of the keys in the thisdict dictionary

译文链接:

标签: #python判断dict #pythondictinkeys