接上节课内容。
三、修改删除字典项
3.1、修改字典项
可以通过引用特定项的键名称来更改其值。
update()方法将使用给定参数中的项目更改字典。参数必须是字典或者是具有键:值对的可迭代对象。
fruits = {
"apple":"crispy",
"orange":"sour",
}
fruits.update({"cherry":"sweet","fig":"delicious"})
print(fruits)
{'apple': 'crispy', 'orange': 'sour', 'cherry': 'sweet', 'fig': 'delicious'}
当键不存在时,这两种方法都会向字典添加新项。
3.2、删除字典项
有几种方法可以从字典中删除项目。
pop()方法删除具有指定键名的项。
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
taste = fruits.pop("apple")
print(taste)
print(fruits)
crispy
{'orange': 'sour', 'cherry': 'sweet'}
popitem()方法删除最后插入的项。
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
fruit,taste = fruits.popitem()
print(fruit,"tastes",taste)
print(fruits)
cherry tastes sweet
{'apple': 'crispy', 'orange': 'sour'}
clear()方法清空字典。
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
fruits.clear()
print(fruits)
{}
四、遍历字典
可以使用for循环遍历字典。
循环遍历字典时,返回值是字典的键,但也有一些方法可以返回值。
逐个打印字典中的所有键名:
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
for fruit in fruits:
print(fruit)
for fruit in fruits.keys():
print(fruit)
apple
orange
cherry
apple
orange
cherry
逐个打印字典中的所有值:
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
for fruit in fruits:
print(fruits[fruit])
for taste in fruits.values():
print(taste)
crispy
sour
sweet
crispy
sour
sweet
通过使用items()方法遍历键和值:
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
for fruit,taste in fruits.items():
print(fruit,"taste",taste)
apple taste crispy
orange taste sour
cherry taste sweet
五、复制字典
不能通过dict2=dict1来复制字典,因为,dict2仅仅是对字典dict1的引用,在dict1中所做的更改也将自动在dict2中生效。
有很多方法可以制作字典副本,一种方法是实用内置的字典方法copy(),还有一种方法是实用内置函数dict().
fruits = {
"apple":"crispy",
"orange":"sour",
"cherry":"sweet",
}
fruits1 = fruits.copy()
print(fruits1)
fruits2 = dict(fruits)
print(fruits2)
{'apple': 'crispy', 'orange': 'sour', 'cherry': 'sweet'}
{'apple': 'crispy', 'orange': 'sour', 'cherry': 'sweet'}
六、字典常用方法
Python有一组可以在字典上使用的内置方法。
方法 | 方法描述 |
clear() | 删除字典的所有元素 |
copy() | 返回字典的副本 |
get() | 返回指定键的值 |
items() | 返回一个列表,其中包含每个键值对的元组 |
keys() | 返回保护字典键的列表 |
pop() | 删除具有指定键的元素 |
popitems() | 删除上次插入的键值对 |
update() | 使用指定的键值对更新字典 |
values() | 返回字典中所有值的列表 |