python学习--------字典
什么是字典
字典以键值对(键和值的组合)的方式把数据组织到一起,我们可以通过键找到与之对应的值并进行操作
例:
student = {'学号':1,
'name': 'xx',
'sex': True,
'adress': '四川成都',
'favorites': ['吃', '喝', '睡'],
'contents':{
'qq': '12344',
'tel': '12345678'
}
}
字典的创建和使用
- 字面量语法
- 构造器函数
- 生成式语法
# 字面量语法
student1 = {
'id': 1010,
'name': '小明',
'sex': 'True',
'birthday': '2000-1-1'
}
# 构造 器函数
student2 = dict(id=1, name='小米', sex=True, birthday='2001-10-1')
print(student1)
print(student2)
# 生成式语法
dict1 = {i: i ** 2 for i in range(1, 10)}
print(dict1)
}
字典的运算
字典中的键必须是不可变类型,例如整数(int
)、浮点数(float
)、字符串(str
)、元组(tuple
)等类型的值;显然,列表(list
)和集合(set
)是不能作为字典中的键的,当然字典类型本身也不能再作为字典中的键,因为字典也是可变类型,但是字典可以作为字典中的值
student1 = {
'id': 1010,
'name': '小明',
'sex': 'True',
'birthday': '2000-1-1'
}
#遍历字典中的键
for key in student1: """
print(key, student1[key])
#遍历字典中的值
for value in student1.values():
print(value)
#遍历字典中的键值对
for key, value in student1.items():
print(key, value)
id 1010
name 小明
sex True
birthday 2000-1-1
1010
小明
True
2000-1-1
id 1010
name 小明
sex True
birthday 2000-1-1
字典的方法
student1 = {
'id': 1010,
'name': '小明',
'sex': 'True',
'birthday': '2000-1-1'
}
print('name' in student1)
print('age' in student1)
#字典的索引运算放在运算符的左边
#如果索引对应的值存在,更新它的值
#如果不存在则添加它的值
student1['name'] = '小米'
student1['address'] = '四川成都'
print(student1)
#使用get函数同过key获得value如果key不存在,不会发生错误会得到一个空值
print(student1.get('age'))
print(student1.get('age', 20))
#删除键值对
# del student1['name']
print(student1.pop('name'))
print(student1.get('name', '无名氏'))
注意:
用del
在删除元素的时候如果指定的键索引不到对应的值,一样会引发KeyError
异常
字典的相关操作
dict1 ={'A': 100, 'B': 200, 'C': 300}
dict2 ={'D': 400, 'E': 500, 'F': 600}
#更新(合并或更新)
dict1.update(dict2)
print(dict1) #{'A': 100, 'B': 200, 'C': 300, 'D': 400, 'E': 500, 'F': 600}
#删除
dict1.pop('B')
print(dict1)#{'A': 100, 'C': 300, 'D': 400, 'E': 500, 'F': 600}
#使用popitem方法删除字典中最后一组键值对并返回对应的二元组
key, value = dict1.popitem()
print(key, value)# F 600
priint(dict1) # {'A': 100, 'C': 300, 'D': 400, 'E': 500}
dict1.setdefault('C')#用setdefault的时候,当键存在时,不能更新它的值
dict1.setdefault('K', 900)#当键不存在时,可以向字典里面存入新的键值对
print(dict1) #{'A': 100, 'C': 300, 'D': 400, 'E': 500, 'K': 900}
#清空所有
dict1.clear()
print(dict1) # {}
练习
输入一段话,统计每个英文字母出现的次数
str1 = 'Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.'
str2 = str1.lower()#转为小写
str2 = str2.replace(',', ' ').replace('.', ' ').replace(' ', '')#将逗号、句号转为空格,然后再消去空格
dict1 = {key: 0 for key in string.ascii_lowercase}#将26个英文字母作为键放入字典中,同时值为0
for ch in str1:
if ch in dict1:
dict1[ch] += 1
for key, value in dict1.items():
print(f'{key}出现了{value}次')
a出现了18次
b出现了5次
c出现了6次
d出现了9次
e出现了27次
f出现了6次
g出现了6次
h出现了13次
i出现了18次
j出现了0次
k出现了1次
l出现了9次
m出现了4次
n出现了21次
o出现了14次
p出现了3次
q出现了0次
r出现了10次
s出现了16次
t出现了16次
u出现了6次
v出现了2次
w出现了2次
x出现了1次
y出现了5次
z出现了0次
练习2:
有如下字典,找出股票值大于100,并添加到新字典里面。找到股票值最大和最小的股票。按照股票价格从高到低给股票排序
stocks = {
‘AAPL’: 191.88,
‘GOOG’: 1186.96,
‘IBM’: 149.24,
‘ORCL’: 48.44,
‘ACN’: 166.89,
‘FB’: 208.09,
‘SYMC’: 21.29
}
stocks = {
'AAPL': 191.88,
'GOOG': 1186.96,
'IBM': 149.24,
'ORCL': 48.44,
'ACN': 166.89,
'FB': 208.09,
'SYMC': 21.29
}
#找出股票值大于100,并添加到新字典里面
dict2 = {key: value for key, value in stocks.items() if value > 100}
print(dict2)
#找到股票值最大和最小的股票
print(max(stocks, key=stocks.get))#指定按照值的大小来找最大值,输出的是最大值对应的键
print(min(stocks, key=stocks.get))
#按照股票价格从高到低给股票排序
print(sorted(stocks, key=stocks.get, reverse=True))#指定按照值的大小来排序,最后输出的是字典的键
{'AAPL': 191.88, 'GOOG': 1186.96, 'IBM': 149.24, 'ACN': 166.89, 'FB': 208.09}
GOOG
SYMC
['GOOG', 'FB', 'AAPL', 'ACN', 'IBM', 'ORCL', 'SYMC']