Python学习笔记:字典dict常用内置函数
字典是 Python
中很重要的数据类型,有很多内置函数需要了解。
1.dict.clear
清除字典中所有键值对。
dict = {'a':10, 'b':20, 'c':30}
dict.clear()
print(dict) # {}
2.dict.get
如果键存在于字典中,则返回该键的值。
如果未找到,则返回 None
。
指定可选参数之后,未找到返回默认值。
dict = {'a':10, 'b':20, 'c':30}
print(dict.get('c')) # 30
print(dict.get('g')) # None
print(dict.get('g', -1)) # -1 指定可选参数
3.dict.items
返回字典中的键值对列表。
items()
返回包含键值对的元组列表。
每个元组中的第一项是键,第二项是键的值。
dict = {'a':10, 'b':20, 'c':30}
dict.items() # dict_items([('a', 10), ('b', 20), ('c', 30)])
list(dict.items()) # [('a', 10), ('b', 20), ('c', 30)]
list(dict.items())[1] # ('b', 20)
list(dict.items())[1][0] # 'b'
4.dict.keys
返回字典中的键列表。
dict = {'a':10, 'b':20, 'c':30}
dict.keys() # dict_keys(['a', 'b', 'c'])
list(dict.keys()) # ['a', 'b', 'c']
5.dict.values
返回字典中的值列表。
dict = {'a':10, 'b':20, 'c':30}
dict.values() # dict_values([10, 20, 30])
list(dict.values()) # [10, 20, 30]
# 即使值重复,也会被多次返回
dict2 = {'a':10, 'b':10, 'c':30}
list(dict2.values()) # [10, 10, 30]
6.dict.pop
从字典中删除一个键,如果它存在,并返回它的值。
如果不存在,则引发异常 KeyError
。
指定可选参数,不存在时返回默认值,不引发异常。
dict = {'a':10, 'b':20, 'c':30}
dict.pop('b') # 20
print(dict) # {'a': 10, 'c': 30}
dict.pop('g')
'''
Traceback (most recent call last):
File "<ipython-input-20-a81e983a7be0>", line 1, in <module>
dict.pop('g')
KeyError: 'g'
'''
dict.pop('g', -1) # -1
7.dict.popitem
从字典中删除最后面的键值对,并返回。
直到字典被删除至空,则引发异常 KeyError
。
dict = {'a':10, 'b':20, 'c':30}
dict.popitem() # ('c', 30)
print(dict) # {'a': 10, 'b': 20}
dict.popitem() # ('b', 20)
print(dict) # {'a': 10}
dict.popitem() # ('a', 10)
print(dict) # {}
dict.popitem()
'''
Traceback (most recent call last):
File "<ipython-input-28-7e744445e3d2>", line 1, in <module>
dict.popitem()
KeyError: 'popitem(): dictionary is empty'
'''
注意:在低于 3.6 的 Python 版本中,popitem( ) 将返回任意(随机)键值对,因为 Python 字典在 3.6 版本之前是无序的。
8.dict.update
将字典与另一个字典或可迭代的键值对合并。
dict = {'a':10, 'b':20, 'c':30}
dict2 = {'b':200, 'd':400}
dict.update(dict2)
print(dict) # {'a': 10, 'b': 200, 'c': 30, 'd': 400}
所有的值都被更新。
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)