Home Backend Development Python Tutorial Python的dict字典结构操作方法学习笔记

Python的dict字典结构操作方法学习笔记

Jun 10, 2016 pm 03:05 PM
dict python dictionary

一.字典的基本方法

1.新建字典

1)、建立一个空的字典

>>> dict1={} 
>>> dict2=dict() 
>>> dict1,dict2 
({}, {}) 


Copy after login

2)、新建的时候初始化一个值

>>> dict1={1:'a',2:'b',3:'c'} 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c'} 

Copy after login

3)、利用元组

>>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c'} 

Copy after login

2、获取方法

1)、get(key) 从字典中获取一个key对应的value,返回value

>>> dict1={1:'a',2:'b',3:'c'} 
>>> dict1.get(1) 
'a' 

Copy after login

如果字典里面不存在,则返回一个 NoneType

>>> type(dict1.get(4)) 
<type 'NoneType'> 

Copy after login

如果要求key值不存在,指定另外一个值返回的话

>>> dict1.get(4,'not found') 
'not found' 

Copy after login

2)、keys() 获取字典中所有的key值,返回一个列表

>>> dict1.keys() 
[1, 2, 3] 

Copy after login

3)、values() 与keys()方法对应,返回的字典中的所有value的列表

>>> dict1.values() 
['a', 'b', 'c'] 

Copy after login

4)、items() 返回一个 (key,value)对应的元组

>>> dict1.items() 
[(1, 'a'), (2, 'b'), (3, 'c')] 

Copy after login

5)、iterkeys() , itervalues() , iteritems() 也是分别获取所有的key,value,(key,value)元祖,只是不在是返回列表,而是一个迭代器

>>> for key in dict1.iterkeys(): 
 print key 
1 
2 
3 
Copy after login


3、设置字典值的方法

1)、直接的方法就是

>>> dict1[4]='d' 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c', 4: 'd'} 

Copy after login

但是,这个方法就是,如果我想添加的key值已经在字典中,那么就会覆盖掉原来的value值

>>> dict1[4]='e' 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c', 4: 'e'} 

Copy after login

2)、setdefault(key,value) 这个方法的好处就是,如果插入的key不存在字典中,那么插入字典并返回该value,否则的存在于字典中的话,那么返回存在的value,不会覆盖掉

>>> dict1 
{1: 'a', 2: 'b', 3: 'c', 4: 'e'} 
>>> dict1.setdefault(5,'f') 
'f' 
>>> dict1.setdefault(5,'g') 
'f' 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c', 4: 'e', 5: 'f'} 

Copy after login

4、删除字典

1)pop(key) 删除指定key的一项,成功返回一个删除项的value, 如果不存在,会抛出异常,所以在用这个方法时候,都要用判断 key是否存在,或者catch这个异常

>>> def pop_key(d,key): 
 try: 
 d.pop(key) 
 print "sucess" 
 except: 
 print "key is not in dict" 
>>> dict1 
{1: 'a', 2: 'b'} 
>>> pop_key(dict1,3) 
key is not in dict 

Copy after login

或者

>>> def sub_dict2(d,key): 
 if d.has_key(key): 
 d.pop(key) 
 print "sucess" 
 else:print "key is not in dict" 
 
>>> pop_key(dict1,3) 
key is not in dict 


Copy after login

这里的has_key(key)就是判断字典里面是否有该key,当然,也可以用 key in d 来代替

2) popitem() 和pop()类似,只是他是删除一个(key,value)的元组

利用上面的方法,可以得使用一些进阶的用法

A、我们通过2个列表来创建一个字典,第一个列表是所有的key,第二个列表是所有的value

>>> list1=[1,2,3] 
>>> list2=['a','b','c'] 
>>> dict1=dict(zip(list1,list2)) 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c'} 

Copy after login

B、找出某一个字典的子字典

>>> dict1 
{1: 'a', 2: 'b', 3: 'c'} 
>>> dict1=dict([(1,'a'),(2,'b'),(3,'c')]) 
>>> dict1 
{1: 'a', 2: 'b', 3: 'c'} 
>>> subkeys=[1,3] 
>>> def sub_dict(d,subkeys): 
 return dict([(k,d.get(k)) for k in subkeys if k in d]) 
 
>>> print sub_dict(dict1,subkeys) 
{1: 'a', 3: 'c'} 
Copy after login

C、反转字典,也就是key变成新字典的value,value变成新字典的key(注意,如果value值有重复,反转后的字典就只会保留一个

>>> def invert_dict(d): 
 return dict([(k,v) for v,k in d.iteritems()]) 
 
>>> print invert_dict(dict1) 
{'a': 1, 'c': 3, 'b': 2} 
>>> 
Copy after login

5、其他基本的方法

1) has_key(key) 判断key是否在字典中

2)copy()返回一个字典的副本(该复制是一个浅复制)

>>> d2={1:[1],2:[2],3:[3]} 
>>> d3=d2.copy() 
>>> d3[1].append(4) 
>>> d2[1] 
[1, 4] 

Copy after login

如果要深复制的话,就要用到copy.deepcopy(a)

>>> d2={1:[1],2:[2],3:[3]} 
>>> import copy 
>>> d3=copy.deepcopy(d2) 
>>> d3[1].append(4) 
>>> print d2[1] , d3[1] 
[1] [1, 4] 

Copy after login

3)clear( ) 清空dict

4)update(d) 用一个字典来跟新另外一个字典,有点类似与2个字典的合并

>>> dict1={1: 'a', 2: 'b', 3: 'c'} 
>>> dict2={1:'x',4:'y'} 
>>> dict1.update(dict2) 
>>> dict1 
{1: 'x', 2: 'b', 3: 'c', 4: 'y'} 
>>> 

Copy after login

二、遍历

字典的遍历方法很多

1、直接利用dict

>>> d 
{'a': 'aa', 'c': 'cc', 'b': 'bb'} 
>>> for i in d: 
 print i,d[i] 
 
a aa 
c cc 
b bb 

Copy after login

2、利用items()

>>> for i,v in d.items(): 
 print i,v 
 
a aa 
c cc 
b bb 

Copy after login

当然也可以这样

>>> for (i,v) in d.items(): 
 print i,v 
 
a aa 
c cc 
b bb 

Copy after login

我印象中有个文章就是比较这2个方法(有括号和没括号)的效率,说字典大小在200以下时候,有括号速度快一点,200以上时候,无括号速度快一点,具体我也没测试。

3、iteritems()
(我觉得比较好的方法)

>>> for k,v in d.iteritems(): 
 print k,v 
 
a aa 
c cc 
b bb 

Copy after login

其他还有些遍历方法,但是我感觉就这3个就足够了


三、一些进阶用法

1、一键多值

一般情况,字典都是一对一映射的,但如果我们需要一对多的映射,比如一本书,我们要统计一些单词出现的页数。那么,可以用list作为dict的value值。在利用setdefault()方法就可以完成

>>> d={'hello':[1,4,9],"good":[1,3,6]} 
>>> d 
{'good': [1, 3, 6], 'hello': [1, 4, 9]} 
>>> d.setdefault('good',[]).append(7) 
>>> d 
{'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} 
>>> d.setdefault('bad',[]).append(2) 
>>> d 
{'bad': [2], 'good': [1, 3, 6, 7], 'hello': [1, 4, 9]} 
>>> 

Copy after login

当然,如果写成一个函数话,就可以更方便的使用,
我们也可以利用set来代替list

>>> def addFunc(d,word,pag): 
 d.setdefault(word,set()).add(pag) 
>>> d={'hello':set([1,4,9]),"good":set([1,3,6])} 
>>> addFunc(d,'hello',8) 
>>> d 
{'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])} 
>>> addFunc(d,'bad',8) 
>>> d 
{'bad': set([8]), 'good': set([1, 3, 6]), 'hello': set([8, 1, 4, 9])} 

Copy after login

2、利用字典完成简单工厂模式
字典的value不单单只是一些常见的字符串,数值,还可以是类和方法,比如我们就可以这样来实现简单工厂模式

>>> class cat(object): 
 def __init__(self): 
 print 'cat init' 
>>> class dog(object): 
 def __init__(self): 
 print 'dag init' 
>>> d={'cat':cat,'dog':dog} 
>>> def factoryFunc(d,name): 
 if name in d: 
 return d[name]() 
 else: 
 raise Exception("error") 
>>> cat=factoryFunc(d,'cat') 
cat init 

Copy after login

另外一个例子,利用变量来控制执行的函数

>>> def deal_cat(): 
 print 'cat run!!' 
 
>>> def deal_dog(): 
 print 'dag run!!' 
 
>>> d={'cat':deal_cat ,'dog':deal_dog } 
>>> animal='cat' 
>>> d[animal]() 
cat run!! 


Copy after login
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

Video Face Swap

Video Face Swap

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

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)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles