Python 入门系列 —— 22. 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.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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值