假期第(12)天

字典
l 字典(
dictionary)是包含若干"键:值"元素的无序可
变序列,字典中的每个元素包含"键"和"值"两部分,
表示一种映射或对应关系,也称关联数组。定义字典
时,每个元素的"键"和"值"用冒号分隔,不同元素之
间用逗号分隔,所有的元素放在一对大括号"{
"和"}
"中
l 字典中的"键"可以是Python中任意不可变数据,例如
整数、实数、复数、字符串、元组等等,但不能使用
列表、集合、字典或其他可变类型作为字典的"键"。
另外,字典中的"键"不允许重复,而"值"可以重复
字典4
2
4
2
字典创建-1
l 赋值运算符"="创建一个字典变量。
>>> a_dict = {'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a_dict
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
l 使用内置函数dict()通过已有数据快速创建字典
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))
>>> print(dictionary)
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典1
>>> x = {} #空字典2
>>> x
{}
>>> type(x) #查看对象类型
<class 'dict'>
字典4
43
3
字典创建-2
l 还可以使用内置函数dict()根据给定的"键:值"来创建
字典:
>>> d = dict(name='Dong', age=37)
>>> d
{'age': 37, 'name': 'Dong'}
l 还可以以给定内容为"键",创建"值"为空(None)的
字典:
>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'age': None, 'name': None, 'sex': None}
字典4
4
44
字典元素的添加与修改-1
l 当以指定"键"为下标为字典元素赋值时的两种含义:
l 若该"键"存在,则表示修改该"键"对应的值;
l 若该"键"不存在,则表示添加一个新的"键:值"元素
>>> aDict
{'age': 35, 'name': 'Dong', 'sex': 'male'}
>>> aDict['age'] = 38 #修改元素值
>>> aDict
{'age': 38, 'name': 'Dong', 'sex': 'male'}
>>> aDict['address'] = 'SDIBT' #添加新元素
>>> aDict
{'age': 38, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}
字典4
5
45
字典元素的添加与修改-2
l 字典对象的update()方法可以将另一个字典的"键:值"
一次性全部添加到当前字典对象,如果两个字典中存
在相同的"键",则以另一个字典中的"值"为准对当前
字典进行更新。
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.items() #返回所有元素
dict_items([('sex', 'male'), ('score', [98, 97]), ('age', 37), ('name',
'Dong')])
>>> aDict.update({'a':97, 'age':39}) #修改"age"键的值,同时添
加新元素"a":97
>>> aDict
{'score': [98, 97], 'sex': 'male', 'a': 97, 'age': 39, 'name': 'Dong'}
字典4
6
46
字典及元素的删除
l 使用d
指 el命令可以删除整个字典,也可以删除字典中
元素。
>>> del aDict['age']
#删除字典元素
>>> aDict
{'score': [98, 97], 'sex': 'male', 'a': 97, 'name': 'Dong'}
>>> del aDict
#删除整个字典
>>> aDict
#字典对象被删除后不再存在
Traceback (most recent call last):
File "<pyshell#291>", line 1, in <module>
aDict
NameError: name 'aDict' is not defined
l 字典对象的pop()和popitem()方法弹出并删除指定元
>>> aDict = {'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.popitem() #弹出一个元素,对空字典会抛出异常
('age', 37)
>>> aDict.pop('sex') #弹出指定键对应的元素
'male'
>>> aDict
字典 {'score': [98, 97], 'name': 'Dong'}4
7
47
字典对象数据的访问-1
l 字典中的每个元素表示一种映射关系或对应关系,根
据提供的"键"作为下标就可以访问对应的"值",如果
字典中不存在这个"键"会抛出异常。
>>> aDict = {'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict['age'] #指定的"键"存在,返回对应的"值"
37
>>> aDict['address'] #指定的"键"不存在,抛出异常
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
aDict['address']
KeyError: 'address'
>>> assert 'address' in aDict, 'Key "address" not in dict' #断言
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
assert 'address' in aDict, 'Key "address" not in dict'
AssertionError: Key "address" not in dict
字典4
8
4
8
字典对象数据的访问-2
l 字典对象提供了一个get()方法用来返回指定"键"对应
的"值",更妙的是这个方法允许指定该键不存在时返
回特定的"值"。
>>> aDict.get('age')
#如果字典中存在该"键"则返回对应的"值"
37
>>> aDict.get('address', 'Not Exists.') #"键"不存在时返回指定值
'Not Exists.'
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
l 字典对象的setdefault()方法用于返回指定"键"对应的"值",如果
字典中不存在该"键",就添加新元素并设置该"键"对应的"值"。
>>> aDict.setdefault('address', 'SDIBT') #增加新元素
'SDIBT'
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'address': 'SDIBT', 'sex':
'male'}
字典4
49
9
字典对象数据的访问-3
l 当对字典对象进行迭代时,默认是遍历字典的"键",
可以使用字典对象的items()方法返回字典中的元素,
即所有"键:值"对,字典对象的keys()方法返回所有"键
",values()方法返回所有"值"。
>>> aDict = {'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> for item in aDict:
#默认遍历字典的"键"
print(item, end=' ')
score age sex Name
>>> for item in aDict.items(): #明确指定遍历字典的元素
print(item, end=' ')
('score', [98, 97]) ('age', 37) ('sex', 'male') ('name', 'Dong')
>>> aDict.items()
dict_items([('age', 37), ('score', [98, 97]), ('name', 'Dong'), ('sex',
'male')])
>>> aDict.keys()
dict_keys(['age', 'score', 'name', 'sex'])
>>> aDict.values()
字典 dict_values([37, [98, 97], 'Dong', 'male'])50
5
0
字典应用示例【
02P50.py】
l 首先生成包含1000个随机字符的字符串,然后统计每
个字符的出现次数
import string
import random
x=string.ascii_letters + string.digits + string.punctuation#标点符号
y=[random.choice(x) for i in range(1000)]#1000个随机字符的列表
z = ''.join(y) #把列表中的字符连接成为字符串
d = dict()
#空字典
for ch in z:
d[ch] = d.get(ch, 0) + 1
#修改每个字符的频次
print(d)
字典51
5
1
字典排序应用示例
l 内置函数sorted()可以对字典元素进行排序并返回新
列表,充分利用key参数可以实现丰富的排序功能
>>> phonebook = {'Linda':'7750', 'Bob':'9345', 'Carol':'5834'}
>>> from operator import itemgetter
>>> sorted(phonebook.items(), key=itemgetter(1))#按"值"排序
[('Carol', '5834'), ('Linda', '7750'), ('Bob', '9345')]
>>> sorted(phonebook.items(), key=itemgetter(0))#按"键"排序
>>> sorted(phonebook.items(), key=lambda item:item[0])#按"键"排
[('Bob', '9345'), ('Carol', '5834'), ('Linda', '7750')]
>>> persons= [ {'name':'Dong', 'age':37}, {'name':'Zhang', 'age':40},
{'name':'Li', 'age':50},{'name':'Dong', 'age':43}]
#使用key来指定排序依据,先按姓名升序排序,姓名相同的按
年龄降序排序,注意,在某一项前面加负号表示降序排序,这
一点只适用于数字类型,不通用
>>> print(sorted(persons, key=lambda x:(x['name'], -x['age'])))
[{'age': 43, 'name': 'Dong'}, {'age': 37, 'name': 'Dong'}, {'age': 50,
'name': 'Li'}, {'age': 40, 'name': 'Zhang'}]
posted @ 2022-01-12 20:12  我的未来姓栗山  阅读(23)  评论(0编辑  收藏  举报