一. 简介
前面简单学习了 python3中字典的创建与遍历,文章如下:
python3的基本数据类型:Dictionary(字典)的创建-优快云博客
本文继续学习 字典的其他操作,例如,字典的增删改等等的操作。
二. python3的基本数据类型:Dictionary(字典)的增删改操作
前面经过学习知道,字典是 python中一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。
下面来学习 字典的增删改等等操作。
1. 遍历查询字典中的键值对
字典方法中有3种方式可以用于提取键值信息。
(1)keys:用于获取字典中的所有键。
(2)values:用于获取字典中的所有值。
(3)itmes:得到字典中的所有键值对。
遍历字典中的键
d = dict(name="魏无羡", height = 183.6, weight = 130, friend="蓝忘机")
for key in d.keys():
print(key)
遍历字典中的值
d = dict(name="魏无羡", height = 183.6, weight = 130, friend="蓝忘机")
for value in d.values():
print(value)
判断某个键是否在字典中:
d = dict(name="肖战", home = "重庆", height = 183.6, weight = 130, friend ="王一博")
if "friend" in d: #查询字典d中是否存在键为"friend"的项
print("friend is in d dictionary!")
else:
print("friend is not in d dictionary!")
2. 向字典中添加新的键值对
向字典中添加新的键值对,下来举例说明:
d = dict(name="肖战", height = 183.6, weight = 130, home ="重庆")
d["friend"] = "王一博"
print(d)
update()方法可以合并两个字典,举例说明:
d1 = dict(name="肖战", home = "重庆", height = 183.6, weight = 130)
d2 = dict(collection = "<我们>", time = "2024-11-11")
d1.update(d2)
print(d1)
结果如下:

3. 删除字典中指定的某个键值对
使用 pop() 方法根据键删除对应的键值对,举例说明:
value = d.pop("friend")
print(value) #获取friend 的值并删除该键值对
删除最后一个键值对,具体实现如下:
value = d.popitem() #获取最后一个键的值并从字典中删除
print(value)
清空字典:使用 clear()方法清除 字典。具体实现如下:
copy_d = d.copy() #创建字典的一个副本
copy_d.clear() #清空副本
4. 修改字典中某个键值对
修改字典中某个值的方法如下:
d = dict(name="肖战", home = "重庆", height = 183.6, weight = 130, friend ="王一博")
d["weight"] = 128
print(d)
注意:如果所修改的键不存在于字典中,则会将键值对添加到字典中。
例如如下代码就会向字典中添加一个新的键值对:
d["age"] = 33
print(d)
输出如下:

关于 python中字典的增删改查暂时学习到这里。
2164

被折叠的 条评论
为什么被折叠?



