字典是python中唯一内建的映射类型。字典中的值并没有特殊的顺序,但是都存储在一个特定的键(key)里。
键可以是数字,字符串甚至是元组。
1. 创建和使用字典
字典可以通过下面的方式创建:
phonebook = {'Alice':'2341','Beth':'9102','Ceil':'3258'}
字典由多个键及与其对应的值构成的对组成。每个键和它的值之间用冒号(:)隔开,项之间用逗号(,)隔开,而整个字典是由一对大括号括起来。空字典:{}
1.1 dict函数
可以用dict函数通过映射(比如其他字典)或者(键,值)这样的序列建立字典。
>>> items = [('name','Gumby'),('age'.42)]
>>> d = dict(items)
>>> d
{'age':42,'name':'Gumby'}
>>> d = dict(name='Gumby','age'=42)
>>> d
{'age':42,'name':'Gumby'}
1.2 基本字典操作
(1)len(d)返回d中项(键-值对)的数量;
(2)d[k]返回关联到k上的值;
(3)d[k]=v将值v关联到键k上;
(4)del d[k]删除键为k的项;
(5)k in d检查d中是否有含键为k的项;
1.3 字典的格式化字符串
字典格式化字符串:在每个转换说明符中的%字符后面,可以加上(用圆括号括起来的)键,后面再跟上其他说明元素。
只要所有给出的键都能在字典中找到,就可以获得任意数量的转换说明符。
>>> temple = ‘the price of cake is $%(cake)s,the price of milk of cake is $%(milk)s. $%(cake)s is OK'
>>> price = {'cake':4,'milk':5}
>>>print temple % price
‘the price of cake is $4,the price of milk of cake is $5. $4 is OK'
1.4 字典方法
1.4.1 clear
clear方法清除字典中所有的项,这是个原地操作,无返回值(或者说返回none)。
考虑下面2种情况:
a.将x关联到一个新的空字典来清空它,这对y一点影响都没有,y还是关联到原先的字典
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key':'value'}
>>> x = {}
>>> y
{'key':'value'}
b.如果想清空原始字典中所有的元素,必须用clear方法。
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key':'value'}
>>> x.clear()
>>> y
{}
1.4.2 copy
copy方法返回一个具有相同键-值对的新字典(这个方法实现的是浅复制,因为值本身是相同的,而不是副本)
在副本中替换值时,原始字典不受影响,但是如果修改了某个值,原始字典会改变。]
>>> x = {'a':1,'b':[2,3,4]}
>>> y = x.copy()
>>> y['a'] = 5
>>> y['b'].remove(3)
>>> y
{'a':5,'b':[2,4]}
>>> x
{'a':1,'b':[2,4]}
避免这个问题的方法是使用深度复制-deepcopy(),复制其包含所有的值。
>>> x = {'a':1,'b':[2,3,4]}
>>> y = x.copy()
>>> z = x.deepcopy()
>>> x['a'].append(5)
>>> y
{'a':1,5,'b':[2,3.4]}
>>> z
{'a':1,'b':[2,3,4]}
1.4.3 fromkeys
fromkeys方法使用给定的键建立新的字典,每个键默认对应的值为None,可以直接在所有字典的类型dict上调用此方法。如果不想使用默认值,也可以自己提供值。
>>> {}.fromkeys(['name','age'])
{'age':None,'name':None}
>>>
>>> dict.fromkeys(['name','age'],'unknow')
{'age':'unknow','name':'unknow'}
1.4.4 get
get方法是个更宽松的访问字典项的方法。当使用get访问一个不存在的键时,会得到None值。还可以自定义“默认”值,替换None。
>>> d = {}
>>> print d.get('name')
None
>>> d.get("name",'N/A')
'N/A'
>>> d[''name] = 'Eric'
>>> d.get('name')
'Eric'
1.4.5 has_key
has_key方法可以检查字典中是否含有给出的键。d.has_key(k)
>>> d = {}
>>> d.has_key('name')
False
1.4.6 items和iteritems
items方法将所有的字典项以列表方式返回,但是列表中的每一项(键,值)返回时并没有特殊的顺序。iteritems方法的作用大致相同,但是会返回一个迭代器对象而不是列表:
>>> d = {'a':1,'b':2,'c':3}
>>>d.items
[('a',1),('b',2),('c',3)]
>>> it = d.iteritems()
>>> it
>>> list(it)
[('a',1),('b',2),('c',3)]
1.4.7 keys和iterkeys
keys方法将字典中的键以列表形式返回,而iterkeys则返回针对键的迭代器。
1.4.8 pop方法
pop方法用来获得对应给定键的值,然后将这个键-值对从字典中移除。
>>> d = {'a':1,'b':2,'c':3}
>>> d.pop('a')
>>> d
{'b':2,'c':3}
1.4.10 setdefault
setdefault方法在某种程度上类似于get方法,就是能够获得与给定键相关联的值,还能在字典中不含有给定键的情况下设定相应的键值。
>>> d = {}
>>> d.setdefault('name','N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d.setdefault('name',A)
'N/A'
如上例,当键存在时,返回默认值(可选)并且相应地更新字典,如果键存在,那么返回与其对应的值,但不改变字典。
1.4.11 update
update方法可以利用一个字典项更新另一个字典。提供的字典项会被添加到旧的字典中,若有相同的键则会进行覆盖。
>>> d = {'a':1,'b':2,'c':3}
>>> x = {'a':5,'d':6}
>>> d.update(x)
>>> d
{'a': 5, 'c': 3, 'b': 2, 'd': 6}
1.4.12 values和itervalues
values方法以列表的形式返回字典中的值(itervalues返回值的迭代器),与返回键的列表不同的是,返回值列表中可以包含重复的元素。
>>> d = {}
>>> d[1]=1
>>> d[2]=2
>>> d[3]=3
>>> d[4]=1
>>> d
{1: 1, 2: 2, 3: 3, 4: 1}
>>> d.values()
[1, 2, 3, 1]

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 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.

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 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.

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 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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools