Home Backend Development Python Tutorial python创建和使用字典实例详解

python创建和使用字典实例详解

Jun 16, 2016 am 08:46 AM

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

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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Introduction to Parallel and Concurrent Programming in Python Introduction to Parallel and Concurrent Programming in Python Mar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

How to Implement Your Own Data Structure in Python How to Implement Your Own Data Structure in Python Mar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and Deserialization of Python Objects: Part 1 Serialization and Deserialization of Python Objects: Part 1 Mar 08, 2025 am 09:39 AM

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Mathematical Modules in Python: Statistics Mathematical Modules in Python: Statistics Mar 09, 2025 am 11:40 AM

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti

See all articles