教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 Python3中的字典

Python3中的字典

发布时间:2021-12-15   编辑:jiaochengji.com
教程集为您提供Python3中的字典等资源,欢迎您收藏本站,我们将为您提供最新的Python3中的字典资源

Python3 字典

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

<pre class="brush:html;toolbar:false">d = {key1 : value1, key2 : value2 }</pre>

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

一个简单的字典实例:

<pre class="brush:html;toolbar:false">dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}</pre>

也可如此创建字典:

<pre class="brush:html;toolbar:false">dict1 = { 'abc': 456 }; dict2 = { 'abc': 123, 98.6: 37 };</pre>

访问字典里的值

把相应的键放入熟悉的方括弧,如下实例:

<pre class="brush:html;toolbar:false">#!/usr/bin/python3 dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'} print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age'])</pre>

以上实例输出结果:

<pre class="brush:html;toolbar:false">dict['Name']:  W3CSchool dict['Age']:  7</pre>

如果用字典里没有的键访问数据,会输出错误如下:

<pre class="brush:html;toolbar:false;">dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'}; print ("dict['Alice']: ", dict['Alice'])</pre>

以上实例输出结果

<pre class="brush:html;toolbar:false">Traceback (most recent call last):   File "test.py", line 5, in <module>     print ("dict['Alice']: ", dict['Alice']) KeyError: 'Alice'</pre>

修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

<pre class="brush:html;toolbar:false">dict = {'Name': 'W3CSchool', 'Age': 7, 'Class': 'First'} dict['Age'] = 8;               # 更新 Age dict['School'] = "W3Cschool教程"  # 添加信息 print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])</pre>

以上实例输出结果

<pre class="brush:html;toolbar:false">dict['Age']:  8 dict['School']:  W3Cschool教程</pre>

您可能感兴趣的文章:
python中如何遍历字典
Python中的有序字典是什么
讲解Python3内置模块之json编码解码方法
Python3中的字典
python3字典中的fromkeys()函数用法
python3如何排序
教你用两种方式遍历循环python中的字典
2019年python学3还是2
python怎么删除字符
python3字典合并怎么做?

[关闭]
~ ~