少儿Python编程进阶教程——字典Dictionaries(8)

少儿Python编程进阶教程——字典Dictionaries(8)

接上节课内容。

三、修改删除字典项

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()返回字典中所有值的列表

微信扫码领取0元编程课


核桃编程-弹窗图

This will close in 180 seconds

少儿编程0元课

 
少儿编程0元课  

少儿素质课推荐

 
少儿素质课推荐  

少儿逻辑0元课

 
少儿逻辑0元课  

公众号

关注公众号

x
少儿编程学习网
专注青少年编程学习、课程推荐、科技特长生规划
2023-06-06 13:19:43
您好,有任何疑问请与我们联系!
您的工单我们已经收到,我们将会尽快跟您联系!
[官方群:675726029]
[Mars老师:Qbit-School]
[Mars老师]
17732463686
取消

选择聊天工具: