Python必备技巧之字典(Dictionary)详解
作者:Mr数据杨 发布时间:2022-02-12 23:01:13
标签:Python,字典,Dictionary
Python中的字典由于是对象的集合属于复合数据类型,类似于列表。
定义字典
字典是 Python 对数据结构的实现,通常称为关联数组。字典由键值对的集合组成。每个键值对将键映射到其关联的值。
可以通过将逗号分隔的键值对列表括在花括号 ( {} ) 中来定义字典。冒号 ( : ) 将每个键与其关联的值分开。
d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
# 定义一个Team
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
可以使用内置dict()函数构建字典。
d = dict([
(<key>, <value>),
(<key>, <value),
.
.
.
(<key>, <value>)
])
# 定义一个Team
>>> MLB_team = dict([
... ('Colorado', 'Rockies'),
... ('Boston', 'Red Sox'),
... ('Minnesota', 'Twins'),
... ('Milwaukee', 'Brewers'),
... ('Seattle', 'Mariners')
... ])
# 另一种定义方式
>>> MLB_team = dict(
... Colorado='Rockies',
... Boston='Red Sox',
... Minnesota='Twins',
... Milwaukee='Brewers',
... Seattle='Mariners'
... )
字典内容的显示。
>>> type(MLB_team)
<class 'dict'>
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
字典中的条目按定义的顺序显示,使用索引无法指定访问元素。
>>> MLB_team[1]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
MLB_team[1]
KeyError: 1
字典的访问
通过在方括号[]中指定对应的键,从字典中检索值。
>>> MLB_team['Minnesota']
'Twins'
>>> MLB_team['Colorado']
'Rockies'
检索值不在字典中则抛出异常。
>>> MLB_team['Toronto']
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
MLB_team['Toronto']
KeyError: 'Toronto'
现有字典添加数据只需分配新的键和值。
>>> MLB_team['Kansas City'] = 'Royals'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners', 'Kansas City': 'Royals'}
更新数据,只需为现有键分配一个新值。
>>> MLB_team['Seattle'] = 'Seahawks'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Seattle': 'Seahawks', 'Kansas City': 'Royals'}
删除数据,使用 del 指定要删除的键。
>>> del MLB_team['Seattle']
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Twins',
'Milwaukee': 'Brewers', 'Kansas City': 'Royals'}
字典键与列表索引
经常遇见的一些错误做法。
>>> MLB_team['Toronto']
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
MLB_team['Toronto']
KeyError: 'Toronto'
>>> MLB_team[1]
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
MLB_team[1]
KeyError: 1
# 数字作为键值使用
>>> d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> d[0]
'a'
>>> d[2]
'c'
不能将字典视为列表。
>>> type(d)
<class 'dict'>
>>> d[-1]
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
d[-1]
KeyError: -1
>>> d[0:2]
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
d[0:2]
TypeError: unhashable type: 'slice'
>>> d.append('e')
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
d.append('e')
AttributeError: 'dict' object has no attribute 'append'
增量构建字典
创建新的空字典,然后通过一次添加一个新的键和值构建。
>>> person = {}
>>> type(person)
<class 'dict'>
>>> person['fname'] = 'Joe'
>>> person['lname'] = 'Fonebone'
>>> person['age'] = 51
>>> person['spouse'] = 'Edna'
>>> person['children'] = ['Ralph', 'Betty', 'Joey']
>>> person['pets'] = {'dog': 'Fido', 'cat': 'Sox'}
# 创建和访问字典
>>> person
{'fname': 'Joe', 'lname': 'Fonebone', 'age': 51, 'spouse': 'Edna',
'children': ['Ralph', 'Betty', 'Joey'], 'pets': {'dog': 'Fido', 'cat': 'Sox'}}
>>> person['fname']
'Joe'
>>> person['age']
51
>>> person['children']
['Ralph', 'Betty', 'Joey']
# 检索字典数据
>>> person['children'][-1]
'Joey'
>>> person['pets']['cat']
'Sox'
构建的字典中数据类型没有明确的限制。
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo[42]
'aaa'
>>> foo[2.78]
'bbb'
>>> foo[True]
'ccc'
字典键的限制
几乎任何类型的值都可以用作 Python 中的字典键。
>>> foo = {42: 'aaa', 2.78: 'bbb', True: 'ccc'}
>>> foo
{42: 'aaa', 2.78: 'bbb', True: 'ccc'}
# 可以使用类型和函数等内置对象
>>> d = {int: 1, float: 2, bool: 3}
>>> d
{<class 'int'>: 1, <class 'float'>: 2, <class 'bool'>: 3}
>>> d[float]
2
>>> d = {bin: 1, hex: 2, oct: 3}
>>> d[oct]
3
同一字典内重复的键无法添加,如果添加则对原键的值进行替换。
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
>>> MLB_team['Minnesota'] = 'Timberwolves'
>>> MLB_team
{'Colorado': 'Rockies', 'Boston': 'Red Sox', 'Minnesota': 'Timberwolves',
'Milwaukee': 'Brewers', 'Seattle': 'Mariners'}
元组也可以是字典键,因为元组是不可变的。
>>> d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
>>> d[(1,1)]
'a'
>>> d[(2,1)]
'c'
字典值的限制
字典的中的值是没有任何限制的。
>>> d = {0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d
{0: 'a', 1: 'a', 2: 'a', 3: 'a'}
>>> d[0] == d[1] == d[2]
True
运算符和内置函数
in and not in运算符返回True or False。
>>> MLB_team = {
... 'Colorado' : 'Rockies',
... 'Boston' : 'Red Sox',
... 'Minnesota': 'Twins',
... 'Milwaukee': 'Brewers',
... 'Seattle' : 'Mariners'
... }
>>> 'Milwaukee' in MLB_team
True
>>> 'Toronto' in MLB_team
False
>>> 'Toronto' not in MLB_team
True
也可以与短路评估一起使用。
>>> MLB_team['Toronto']
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
MLB_team['Toronto']
KeyError: 'Toronto'
>>> 'Toronto' in MLB_team and MLB_team['Toronto']
False
内置字典方法
与字符串和列表一样字典上也是有调用内置方法。
# d.clear() 清空字典数据
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> d.clear()
>>> d
{}
# d.get(<key>[, <default>]) 如果字典中存在键,则返回该键的值
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> print(d.get('b'))
20
>>> print(d.get('z'))
None
# <key>未找到并且<default>指定了可选参数
>>> print(d.get('z', -1))
-1
# d.items() 返回字典中的键值对列表
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.items())
[('a', 10), ('b', 20), ('c', 30)]
>>> list(d.items())[1][0]
'b'
>>> list(d.items())[1][1]
20
# d.keys() 返回字典中的键列表
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.keys())
['a', 'b', 'c']
# d.values() 返回字典中的值列表
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d
{'a': 10, 'b': 20, 'c': 30}
>>> list(d.values())
[10, 20, 30]
# d.pop(<key>[, <default>]) 从字典中删除一个键,如果存在并返回它的值
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('b')
20
>>> d
{'a': 10, 'c': 30}
# 如果不存在则引发异常
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z')
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
d.pop('z')
KeyError: 'z'
# 如果指定默认参数<default>则返回该值
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.pop('z', -1)
-1
>>> d
{'a': 10, 'b': 20, 'c': 30}
# d.popitem() 从字典中删除键值对
>>> d = {'a': 10, 'b': 20, 'c': 30}
>>> d.popitem()
('c', 30)
>>> d
{'a': 10, 'b': 20}
>>> d.popitem()
('b', 20)
>>> d
{'a': 10}
# d为空会引发异常
>>> d = {}
>>> d.popitem()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
d.popitem()
KeyError: 'popitem(): dictionary is empty'
# d.update(<obj>) 将字典与另一个字典或可迭代的键值对合并
# (被替换键值).update(替换键值)
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d2 = {'b': 200, 'd': 400}
>>> d1.update(d2)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
# 使用元组更新
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update([('b', 200), ('d', 400)])
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
# 指定关键字参数
>>> d1 = {'a': 10, 'b': 20, 'c': 30}
>>> d1.update(b=200, d=400)
>>> d1
{'a': 10, 'b': 200, 'c': 30, 'd': 400}
来源:https://blog.csdn.net/qq_20288327/article/details/123706867


猜你喜欢
- 一 multiprocessing模块介绍python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu\_cou
- 本文实例讲述了PHP实现登录,注册及密码修改功能的方法。分享给大家供大家参考,具体如下:这里介绍注册,登录,修改密码的界面布局与功能实现:1
- 今日给大家分享一个Python读取Excel表格,同时采用表格中的数值画图柱状图和折线图,这里只需要几行代码便可以实。首先我们需要安装一个E
- 本文实例讲述了JS获取日期的方法。分享给大家供大家参考,具体如下:原理很简单,一天的时间的毫秒数是1000*60*60*24,前n天的日期就
- 本文实例讲述了Python爬虫实现抓取京东店铺信息及下载图片功能。分享给大家供大家参考,具体如下:这个是抓取信息的from bs4 impo
- 这不仅仅是一个信息 * 的时代,也是一个服务 * 的时代。一切都是因为互联网,随着互联网技术的发展,信息的增多,服务的增多,用户需求的多样化。怎
- 如果使用的是matplotlib绘图,可以通过以下命令更改图片的大小:%matplotlib linline如果是 plt.figure(f
- 一些很实用且必用的js小脚本代码:脚本1:进入页面后自动播放音乐或其它声音文件<embed src="音乐地址&q
- 熟悉js的朋友很多都遇到过js的数组与字符串相互转换的情况,本文就此作一简单介绍,示例如下:一、数组转字符串需要将数组元素用某个字符连接成字
- 前言最近想做个小玩意,需要在mac端实现屏幕截图,搜了下网上中文资源都比较老旧,于是查了下,发现有些好用的Python库已经支持Mac 以及
- vue3.0 beta 版本已经发布有一阵子了,是时候上手体验一波了~注意,本文所有演示都是基于 vue3.0 beta 版本,不保证后续正
- 一、前言本篇博客对于文件操作、字典、列表、匿名函数以及sort()等内置函数进行了系统的整理操作,以设计一个学生信息管理系统的形式展示,具体
- 好吧,我承认我是对晚上看到一张合适的票转让但打过电话去说已经被搞走了这件事情感到蛋疼。直接上文件吧。#coding: utf-8'&
- 准备必须环境:Python3开始先实现一个简单的版本,直接上代码:import urllib.requestimport urllib.er
- 前言本文旨在用最通俗的语言讲述最枯燥的基本知识这个话题比较有意思。昨天中午吃完饭间突然有个同事蹦出了一句:“like有索引吗?”,我顺口就说
- (1)、函数y = sin(x)(2)、数据准备#数据准备X=np.arange(-np.pi,np.pi,1) #定义样本点X,从-pi到
- 本文记录django中如何使用celery完成异步任务。Celery 是一个简单、灵活且可靠的,处理大量消息的分布式系统,并且提供维护这样一
- 能评估使用方法性能评估模块提供了一系列用于模型性能评估的函数,这些函数在模型编译时由metrics关键字设置性能评估函数类似与目标函数, 只
- 在用python进行图像处理时,有时需要遍历numpy数组,下面是遍历数组的方法:[rows, cols] = num.shape for
- Python获取图片的大小了解过Pillow的都知道,Pillow是一个非常强大的图片处理器,这篇文章主要记录一下Pillow对图片信息的获