search
HomeBackend DevelopmentPython Tutorialpython中的字典详细介绍

一、什么是字典?

字典是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
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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.