Python中如何定义字典
发表于:2025-11-15 作者:千家信息网编辑
千家信息网最后更新 2025年11月15日,这篇文章主要讲解了"Python中如何定义字典",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"Python中如何定义字典"吧!Python中的字典由于是
千家信息网最后更新 2025年11月15日Python中如何定义字典
这篇文章主要讲解了"Python中如何定义字典",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"Python中如何定义字典"吧!
Python中的字典由于是对象的集合属于复合数据类型,类似于列表。
定义字典
字典是 Python 对数据结构的实现,通常称为关联数组。字典由键值对的集合组成。每个键值对将键映射到其关联的值。

可以通过将逗号分隔的键值对列表括在花括号 ( {} ) 中来定义字典。冒号 ( : ) 将每个键与其关联的值分开。
d = { : , : , . . . : }# 定义一个Team>>> MLB_team = {... 'Colorado' : 'Rockies',... 'Boston' : 'Red Sox',... 'Minnesota': 'Twins',... 'Milwaukee': 'Brewers',... 'Seattle' : 'Mariners'... } 可以使用内置dict()函数构建字典。
d = dict([ (, ), ( , , )])# 定义一个Team>>> MLB_team = dict([... ('Colorado', 'Rockies'),... ('Boston', 'Red Sox'),... ('Minnesota', 'Twins'),... ('Milwaukee', 'Brewers'),... ('Seattle', 'Mariners')... ])# 另一种定义方式>>> MLB_team = dict(... Colorado='Rockies',... Boston='Red Sox',... Minnesota='Twins',... Milwaukee='Brewers',... Seattle='Mariners'... )
字典内容的显示。
>>> type(MLB_team)>>> MLB_team{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins','Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
字典中的条目按定义的顺序显示,使用索引无法指定访问元素。
>>> MLB_team[1]Traceback (most recent call last): File "", line 1, in MLB_team[1]KeyError: 1
字典的访问
通过在方括号[]中指定对应的键,从字典中检索值。
>>> MLB_team['Minnesota']'Twins'>>> MLB_team['Colorado']'Rockies'
检索值不在字典中则抛出异常。
>>> MLB_team['Toronto']Traceback (most recent call last): File "", line 1, in MLB_team['Toronto']KeyError: 'Toronto'
现有字典添加数据只需分配新的键和值。
>>> MLB_team['Kansas City'] = 'Royals'>>> MLB_team{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins','Milwaukee': 'Brewers', 'Seattle': 'Mariners', 'Kansas City': 'Royals'}更新数据,只需为现有键分配一个新值。
>>> MLB_team['Seattle'] = 'Seahawks'>>> MLB_team{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins','Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}删除数据,使用 del 指定要删除的键。
>>> del MLB_team['Seattle']>>> MLB_team{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins','Milwaukee': 'Brewers', 'Kansas City': 'Royals'}字典键与列表索引
经常遇见的一些错误做法。
>>> MLB_team['Toronto']Traceback (most recent call last): File "", line 1, in MLB_team['Toronto']KeyError: 'Toronto'>>> MLB_team[1]Traceback (most recent call last): File " ", line 1, in MLB_team[1]KeyError: 1# 数字作为键值使用>>> d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}>>> d{0: 'a', 1: 'b', 2: 'c', 3: 'd'}>>> d[0]'a'>>> d[2]'c'
不能将字典视为列表。
>>> type(d)>>> d[-1]Traceback (most recent call last): File " ", line 1, in d[-1]KeyError: -1>>> d[0:2]Traceback (most recent call last): File " ", line 1, in d[0:2]TypeError: unhashable type: 'slice'>>> d.append('e')Traceback (most recent call last): File " ", line 1, in d.append('e')AttributeError: 'dict' object has no attribute 'append'
增量构建字典
创建新的空字典,然后通过一次添加一个新的键和值构建。
>>> person = {}>>> type(person)>>> person['fname'] = 'Joe'>>> person['lname'] = 'Fonebone'>>> person['age'] = 51>>> person['spouse'] = 'Edna'>>> person['children'] = ['Ralph', 'Betty', 'Joey']>>> person['pets'] = {'dog': 'Fido', 'cat': 'Sox'}# 创建和访问字典>>> person{'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna','children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}}>>> person['fname']'Joe'>>> person['age']51>>> person['children']['Ralph', 'Betty', 'Joey']# 检索字典数据>>> person['children'][-1]'Joey'>>> person['pets']['cat']'Sox' 构建的字典中数据类型没有明确的限制。
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}>>> foo{42: 'aaa', 2.78: 'bbb', True: 'ccc'}>>> foo[42]'aaa'>>> foo[2.78]'bbb'>>> foo[True]'ccc'字典键的限制
几乎任何类型的值都可以用作 Python 中的字典键。
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}>>> foo{42: 'aaa', 2.78: 'bbb', True: 'ccc'}# 可以使用类型和函数等内置对象>>> d = {int: 1, float: 2, bool: 3}>>> d{: 1, : 2, : 3}>>> d[float]2>>> d = {bin: 1, hex: 2, oct: 3}>>> d[oct]3 同一字典内重复的键无法添加,如果添加则对原键的值进行替换。
>>> MLB_team = {... 'Colorado' : 'Rockies',... 'Boston' : 'Red Sox',... 'Minnesota': 'Twins',... 'Milwaukee': 'Brewers',... 'Seattle' : 'Mariners'... }>>> MLB_team['Minnesota'] = 'Timberwolves'>>> MLB_team{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Timberwolves','Milwaukee': 'Brewers', 'Seattle': 'Mariners'}元组也可以是字典键,因为元组是不可变的。
>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}>>> d[(1,1)]'a'>>> d[(2,1)]'c'字典值的限制
字典的中的值是没有任何限制的。
>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}>>> d{0: 'a', 1: 'a', 2: 'a', 3: 'a'}>>> d[0] == d[1] == d[2]True运算符和内置函数
in and not in运算符返回True or False。
>>> MLB_team = {... 'Colorado' : 'Rockies',... 'Boston' : 'Red Sox',... 'Minnesota': 'Twins',... 'Milwaukee': 'Brewers',... 'Seattle' : 'Mariners'... }>>> 'Milwaukee' in MLB_teamTrue>>> 'Toronto' in MLB_teamFalse>>> 'Toronto' not in MLB_teamTrue也可以与短路评估一起使用。
>>> MLB_team['Toronto']Traceback (most recent call last): File "", line 1, in MLB_team['Toronto']KeyError: 'Toronto'>>> 'Toronto' in MLB_team and MLB_team['Toronto']False
内置字典方法
与字符串和列表一样字典上也是有调用内置方法。
# d.clear() 清空字典数据>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d{'a': 10, 'b': 20, 'c': 30}>>> d.clear()>>> d{}# d.get([, ]) 如果字典中存在键,则返回该键的值>>> d = {'a': 10, 'b': 20, 'c': 30}>>> print(d.get('b'))20>>> print(d.get('z'))None# 未找到并且指定了可选参数>>> print(d.get('z', -1))-1# d.items() 返回字典中的键值对列表>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d{'a': 10, 'b': 20, 'c': 30}>>> list(d.items())[('a', 10), ('b', 20), ('c', 30)]>>> list(d.items())[1][0]'b'>>> list(d.items())[1][1]20# d.keys() 返回字典中的键列表>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d{'a': 10, 'b': 20, 'c': 30}>>> list(d.keys())['a', 'b', 'c']# d.values() 返回字典中的值列表>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d{'a': 10, 'b': 20, 'c': 30}>>> list(d.values())[10, 20, 30]# d.pop([, ]) 从字典中删除一个键,如果存在并返回它的值>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d.pop('b')20>>> d{'a': 10, 'c': 30}# 如果不存在则引发异常>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d.pop('z')Traceback (most recent call last): File "", line 1, in d.pop('z')KeyError: 'z'# 如果指定默认参数则返回该值>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d.pop('z', -1)-1>>> d{'a': 10, 'b': 20, 'c': 30}# d.popitem() 从字典中删除键值对>>> d = {'a': 10, 'b': 20, 'c': 30}>>> d.popitem()('c', 30)>>> d{'a': 10, 'b': 20}>>> d.popitem()('b', 20)>>> d{'a': 10}# d为空会引发异常>>> d = {}>>> d.popitem()Traceback (most recent call last): File "", line 1, in d.popitem()KeyError: 'popitem(): dictionary is empty'# d.update() 将字典与另一个字典或可迭代的键值对合并# (被替换键值).update(替换键值)>>> d1 = {'a': 10, 'b': 20, 'c': 30}>>> d2 = {'b': 200, 'd': 400}>>> d1.update(d2)>>> d1{'a': 10, 'b': 200, 'c': 30, 'd': 400}# 使用元组更新>>> d1 = {'a': 10, 'b': 20, 'c': 30}>>> d1.update([('b', 200), ('d', 400)])>>> d1{'a': 10, 'b': 200, 'c': 30, 'd': 400}# 指定关键字参数>>> d1 = {'a': 10, 'b': 20, 'c': 30}>>> d1.update(b=200, d=400)>>> d1{'a': 10, 'b': 200, 'c': 30, 'd': 400} 感谢各位的阅读,以上就是"Python中如何定义字典"的内容了,经过本文的学习后,相信大家对Python中如何定义字典这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
字典
数据
类型
限制
内容
函数
参数
关联
学习
检索
只需
对象
方法
索引
运算符
分配
更新
运算
中指
做法
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
华为x6800服务器管理
网络安全攻防平台解密关
闵行区海航软件开发内容
手机的基岩版怎么加入服务器
数据库性能优化究竟该如何下手
软件开发什么最挣钱
软件开发场景图片
服务器网卡不能使用网口灯亮
软件开发易学吗
云服务器独立服务器
网络安全与执法专业属于公安吗
互联网医疗科技潜力股
路测软件开发
海峡网络安全
自学网络的软件开发
秀洲区网络安全滴水成泉
关于数据库的毕业论文
未连接弹幕服务器
西安银行网络安全测试招投标
甘肃智慧党建软件开发
北京世纪中彩网络技术有限公
近年来软件开发的参考文献
贵阳盛世加贝网络技术怎么样
刺激战场国服服务器繁忙是啥意思
网络安全讨论发言提纲
国产软件开发服务股票
明远软件开发案例
软件开发需要版本管理
软件开发的财务成本是什么
若依多数据库类型分页