Home Backend Development Python Tutorial python中的字典详细介绍

python中的字典详细介绍

Jun 06, 2016 am 11:33 AM
python dictionary

一、什么是字典?

字典是Python语言中唯一的映射类型。

映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希表。

字典对象是可变的,它是一个容器类型,能存储任意个数的Python对象,其中也可包括其他容器类型。

字典类型与序列类型的区别:

1.存取和访问数据的方式不同。
2.序列类型只用数字类型的键(从序列的开始按数值顺序索引);
3.映射类型可以用其他对象类型作键(如:数字、字符串、元祖,一般用字符串作键),和序列类型的键不同,映射类型的键直4.接或间接地和存储数据值相关联。
5.映射类型中的数据是无序排列的。这和序列类型是不一样的,序列类型是以数值序排列的。
6.映射类型用键直接“映射”到值。

字典是Python中最强大的数据类型之一。

二、如何创建字典和给字典赋值

简单地说字典就是用大括号包裹的键值对的集合。(键值对也被称作项)
一般形式:

代码如下:


adict = {}
adict = {key1:value2, key2:value2, …}


或用dict()函数,如,adict = dict() 或 adict = dict((['x',1],['y',2]))这样写对吗?adict = dict(['x',1],['y',2])。关键字参数创建字典,如:adict= dict(name='allen',age='40′)
或用fromkeys()方法,如,adict = {}.fromkeys((‘x','y'), -1) 这样创建的字典的value是一样的,若不给值,默认为None。

特点:
1、键与值用冒号“:”分开;
2、项与项用逗号“,”分开;
3、字典中的键必须是唯一的,而值可以不唯一。

代码如下:


adict = {‘name':'allen', ‘name':'lucy', ‘age':'40′} 与 bdict = {‘name':'allen', ‘name2′:'allen', ‘age':'40′}


注意:如果字典中的值为数字,最好使用字符串数字形式,如:'age':'040′ 而不用 ‘age':040

三、字典的基本操作

1、如何访问字典中的值?
adict[key] 形式返回键key对应的值value,如果key不在字典中会引发一个KeyError。

2、如何检查key是否在字典中?

a、has_key()方法 形如:adict.haskey(‘name') 有–>True,无–>False
b、in 、not in   形如:'name' in adict      有–>True,无–>False

3、如何更新字典?

a、添加一个数据项(新元素)或键值对
adict[new_key] = value 形式添加一个项
b、更新一个数据项(元素)或键值对
adict[old_key] = new_value
c、删除一个数据项(元素)或键值对
del adict[key] 删除键key的项 / del adict 删除整个字典
adict.pop(key) 删除键key的项并返回key对应的 value值

四、映射类型操作符

标准类型操作符(+,-,*,,=,==,!=,and,or, not)

a、字典不支持拼接和重复操作符(+,*)
b、字典的比较操作
先比较字典的长度也就是字典的元素个数
键比较
值比较
例子:

代码如下:


adict = {}
bdict = {‘name':'allen', ‘age':'40′}
cmp(adict, bdict)  -1 or > –>1 or ==  –>0

五、映射相关的函数

1、len() 返回字典的长度
2、hash() 返回对象的哈希值,可以用来判断一个对象能否用来作为字典的键
3、dict() 工厂函数,用来创建字典

六、字典的方法

1、adict.keys() 返回一个包含字典所有KEY的列表;
2、adict.values() 返回一个包含字典所有value的列表;
3、adict.items() 返回一个包含所有(键,值)元祖的列表;
4、adict.clear() 删除字典中的所有项或元素;
5、adict.copy() 返回一个字典浅拷贝的副本;
6、adict.fromkeys(seq, val=None) 创建并返回一个新字典,以seq中的元素做该字典的键,val做该字典中所有键对应的初始值(默认为None);
7、adict.get(key, default = None) 返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None);
8、adict.has_key(key) 如果key在字典中,返回True,否则返回False。 现在用 in 、 not in;
9、adict.iteritems()、adict.iterkeys()、adict.itervalues() 与它们对应的非迭代方法一样,不同的是它们返回一个迭代子,而不是一个列表;
10、adict.pop(key[,default]) 和get方法相似。如果字典中存在key,删除并返回key对应的vuale;如果key不存在,且没有给出default的值,则引发keyerror异常;
11、adict.setdefault(key, default=None) 和set()方法相似,但如果字典中不存在Key键,由 adict[key] = default 为它赋值;
12、adict.update(bdict) 将字典bdict的键值对添加到字典adict中。

七、字典的遍历

1、遍历字典的key(键)

代码如下:


for key in adict.keys():print key


2、遍历字典的value(值)

代码如下:


for value in adict.values(): print value


3、遍历字典的项(元素)

代码如下:


for item in adict.items():print item


4、遍历字典的key-value

代码如下:


for item,value in adict.items(): print ‘key=%s, value=%s' %(item, value)  或   for item,value in adict.iteritems(): print ‘key=%s, value=%s' %(item, value)


注意:for item,value in adict.items(): print ‘key=%s', ‘value=%s', %(item, value) 这种写法是错误的

八、使用字典的注意事项

1、不能允许一键对应多个值;
2、键必须是可哈希的。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

How to convert XML to PDF on your phone with high quality? How to convert XML to PDF on your phone with high quality? Apr 02, 2025 pm 09:48 PM

Convert XML to PDF with high quality on your mobile phone requires: parsing XML in the cloud and generating PDFs using a serverless computing platform. Choose efficient XML parser and PDF generation library. Handle errors correctly. Make full use of cloud computing power to avoid heavy tasks on your phone. Adjust complexity according to requirements, including processing complex XML structures, generating multi-page PDFs, and adding images. Print log information to help debug. Optimize performance, select efficient parsers and PDF libraries, and may use asynchronous programming or preprocessing XML data. Ensure good code quality and maintainability.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

See all articles