
01
引言
在Python中,字典Dict是常用的数据类型之一,本文就字典中相关常见的函数和操作进行汇总,方便大家查漏补缺。
闲话少说,我们直接开始吧!
02
创建字典
我们一般使用花括号创建列表,如下所示:
d = {}
需要明确的是在Python中,我们一般使用花括号{ 和 } 来表示字典。
当然我们也可以创建包含初始值的字典,如下所示:
d = {"apple":4, "orange":5, "pear":6}
字典中包含多个键值对,它们之间用逗号 , 分隔其中键和值之间用冒号 : 进行分隔。
键"apple"的值 value 为数字4
键"orange" 的值 value 为数字5
键"pear" 的值 value 为数字6
03
根据key获取相应的值
d = {"apple":4, "orange":5, "pear":6}
上述字典中,"apple" 的价格为4, "orange" 的价格为5,"pear" 的价格为6,我们可以直接通过索引来获取相应key的value值,如下所示:
apple_price = d["apple"] # apple_price will be 4orange_price = d["orange"] # orange_price will be 5pear_price = d["pear"] # pear_price will be 6
简单来说,我们可以简单地使用语法 d[key] 来获取某个key的value值。
04
添加新的键值对
d = {"apple":4, "orange":5, "pear":6}
d["durian"] = 7
上述代码运行后,字典 d 内的内容如下:
d = {"apple":4, "orange":5, "pear":6, "durian":7}
05
更新某个key对应的value值
d = {"apple":4, "orange":5, "pear":6}
d["apple"] = 10
d = {"apple":10, "orange":5, "pear":6}
06
字典中删除键值对
d = {"apple":4, "orange":5, "pear":6}
del d["apple"]
d = {"orange":5, "pear":6}
07
计算字典的长度
一般来说字典的长度指的是字典中所拥有的键值对的数量。如果我们需要得到字典的长度,我们一般使用内置的函数 len,如下所示:
d = {"apple":4, "orange":5, "pear":6}length = len(d)# length will be 3
08
遍历字典
如果我们需要对上述字典进行遍历访问:
d = {"apple":4, "orange":5, "pear":6}
最常用的使用 for 循环进行访问的方法如下:
for key in d:value = d[key]print(key, value)
上述代码的运行结果如下:
apple 4orange 5pear 6
当然我们也可以使用内置的 items() 函数来直接获取相应的value 值,如下:
for key, value in d.items():print(key, value)
上述代码的运行结果如下:
apple 4orange 5pear 6
09
判断字典中包含某键key
假设我们有如下字典:
d = {"apple":4, "orange":5, "pear":6}
如果我们需要核实键"apple"是否存在上述字典d中,我们一般使用in来进行上述操作。
样例代码如下:
if "apple" in d:print("the key apple exists")else:print("the key apple does not exist")
10
判断字典中包含某值value
假设我们有如下字典:
d = {"apple":4, "orange":5, "pear":6}
如果我们需要核实值 4 是否存在上述字典 d 中,此时我们可以使用函数
values() 来进行上述操作:
if 4 in d.values():print("the value 4 exists")else:print("the value 4 does not exist")
11
总结
本文重点介绍了Python中字典dict 常见的操作和相应的应用场景,并给出了相关代码示例。
您学废了吗?
点击上方小卡片关注我
万水千山总关情,点个在看行不行。

