字典是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]

ThedifferencebetweenaforloopandawhileloopinPythonisthataforloopisusedwhenthenumberofiterationsisknowninadvance,whileawhileloopisusedwhenaconditionneedstobecheckedrepeatedlywithoutknowingthenumberofiterations.1)Forloopsareidealforiteratingoversequence

In Python, for loops are suitable for cases where the number of iterations is known, while loops are suitable for cases where the number of iterations is unknown and more control is required. 1) For loops are suitable for traversing sequences, such as lists, strings, etc., with concise and Pythonic code. 2) While loops are more appropriate when you need to control the loop according to conditions or wait for user input, but you need to pay attention to avoid infinite loops. 3) In terms of performance, the for loop is slightly faster, but the difference is usually not large. Choosing the right loop type can improve the efficiency and readability of your code.

In Python, lists can be merged through five methods: 1) Use operators, which are simple and intuitive, suitable for small lists; 2) Use extend() method to directly modify the original list, suitable for lists that need to be updated frequently; 3) Use list analytical formulas, concise and operational on elements; 4) Use itertools.chain() function to efficient memory and suitable for large data sets; 5) Use * operators and zip() function to be suitable for scenes where elements need to be paired. Each method has its specific uses and advantages and disadvantages, and the project requirements and performance should be taken into account when choosing.

Forloopsareusedwhenthenumberofiterationsisknown,whilewhileloopsareuseduntilaconditionismet.1)Forloopsareidealforsequenceslikelists,usingsyntaxlike'forfruitinfruits:print(fruit)'.2)Whileloopsaresuitableforunknowniterationcounts,e.g.,'whilecountdown>

ToconcatenatealistoflistsinPython,useextend,listcomprehensions,itertools.chain,orrecursivefunctions.1)Extendmethodisstraightforwardbutverbose.2)Listcomprehensionsareconciseandefficientforlargerdatasets.3)Itertools.chainismemory-efficientforlargedatas

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
