search
HomeBackend DevelopmentPython TutorialPython 字典(Dictionary)操作详解

Python 字典(Dictionary)操作详解

Jun 16, 2016 am 08:44 AM
pythonpython dictionary operations

Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型。
一、创建字典
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:

复制代码 代码如下:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
也可如此创建字典:
复制代码 代码如下:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
注意:
每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。
值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。
二、访问字典里的值
把相应的键放入熟悉的方括弧,如下实例:
复制代码 代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
#以上实例输出结果:

#dict['Name']:  Zara
#dict['Age']:  7


如果用字典里没有的键访问数据,会输出错误如下:
复制代码 代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

print "dict['Alice']: ", dict['Alice'];
#以上实例输出结果:

#dict['Zara']:
#Traceback (most recent call last):
#  File "test.py", line 4, in
#    print "dict['Alice']: ", dict['Alice'];
#KeyError: 'Alice'[/code]
三、修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

复制代码 代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

 
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#以上实例输出结果:
#dict['Age']:  8
#dict['School']:  DPS School
四、删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
复制代码 代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

del dict['Name']; # 删除键是'Name'的条目
dict.clear();     # 清空词典所有条目
del dict ;        # 删除词典

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#但这会引发一个异常,因为用del后字典不再存在:

dict['Age']:
#Traceback (most recent call last):
#  File "test.py", line 8, in
#    print "dict['Age']: ", dict['Age'];
#TypeError: 'type' object is unsubscriptable


五、字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
复制代码 代码如下:
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};

print "dict['Name']: ", dict['Name'];
#以上实例输出结果:
#dict['Name']:  Manni
2)键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行,如下实例:
复制代码 代码如下:
#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7};

print "dict['Name']: ", dict['Name'];
#以上实例输出结果:

#Traceback (most recent call last):
#  File "test.py", line 3, in
#    dict = {['Name']: 'Zara', 'Age': 7};
#TypeError: list objects are unhashable


六、字典内置函数&方法
Python字典包含了以下内置函数:
1、cmp(dict1, dict2):比较两个字典元素。
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串表示。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:
1、radiansdict.clear():删除字典内所有元素
2、radiansdict.copy():返回一个字典的浅复制
3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
5、radiansdict.has_key(key):如果键在字典dict里返回true,否则返回false
6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
7、radiansdict.keys():以列表返回一个字典所有的键
8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
10、radiansdict.values():以列表返回字典中的所有值

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.