一、字典的定义
字典是一个无序的数据集合,使用print输出字典的时候
通常输出的顺序和定义的顺序是不一致的
1.列表类型的转换
将两个列表类型转换为一个列表
也可以转换为字典类型
users = ['user1','user2']
passwd = ['123','456']
print(zip(users,passwd)) 该类型不能够正确输出
print(list(zip(users,passwd))) 将两个列表转换为一个列表来输出
print(dict(zip(users,passwd))) 两个列表转换为字典键值对输出
s = {} 定义字典为空
print(type(s)) 输出类型为字典
<zip object at 0x7f683e43f7c8>
[(‘user1’, ‘123’), (‘user2’, ‘456’)]
{‘user1’: ‘123’, ‘user2’: ‘456’}
<class ‘dict’>
字典:key - value 键值对
value可以是任意数据类型
s = {
'linux':[100,99,88],
'westos':[190,564,645]
}
print(s,type(s))
{‘linux’: [100, 99, 88], ‘westos’: [190, 564, 645]} <class ‘dict’>
工厂函数
d = dict() dict为一个函数
print(type(d)) 查看d的类型
d1 = dict(a=1,b=2)
print(d1,type(d1))
<class ‘dict’> 查看到的类型为字典类型
{‘a’: 1, ‘b’: 2} <class ‘dict’>
字典的嵌套
定义学生students,在其中定义457801和457802两名学生,在这两名学生中又可以定义更多的信息来实现字典的嵌套
students = {
'457801':{
'name':'wsp',
'age':18,
'score':80
},
'457802':{
'name': 'kiki',
'age': 30,
'score': 59
}
}
print(students['457802']['name']
kiki
所有的key值和value值是一样的
print({}.fromkeys({'1','2'},'000000')) 1和2所对应的value值是一样的
{‘1’: ‘000000’, ‘2’: ‘000000’}
二、字典的特性
- 字典不支持索引
- 字典不支持切片
- 字典的重复和连接无意义
d = {
‘1’:‘a’,
‘2’:‘b’
}
print(d[0])
print(d[:])
强行输出字典的索引和切片会有类型报错
成员操作符
操作对象是key值,只能查看key值是否存在
print('1' in d) 查看1在不在d的key值中
print('a' in d) 查看a在不在key值中
True 1在key值中
False a不在key值中
for循环,默认遍历字典的key值
d = {
'1':'a',
'2':'b'
}
for i in d:
print(i)
1
2
遍历字典
i是键值,d[i]是key值所对应的value值
d = {
'1':'a',
'2':'b'
}
for i in d:
print(i,d[i])
1 a
2 b
三、字典的增加
定义一个字典
services = {
‘http’:80,
‘ftp’:21,
‘ssh’:22
}
增加一个元素
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应key-value
services['mysql'] = 3306
print(services)
services['http'] = 443
print(services)
{‘http’: 80, ‘ftp’: 21, ‘ssh’: 22, ‘mysql’: 3306} mysql不存在在字典中,就添加
{‘http’: 443, ‘ftp’: 21, ‘ssh’: 22, ‘mysql’: 3306} http’在字典中有存在的key值就更新value值
添加多个key-value值
services = {
'http':80,
'ftp':21,
'ssh':22
}
services_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
services.update(services_backup)
print(services)
#多个key-value值的添加和单个添加的规则一样,如果存在key值就更新,不存在就添加新的
services.update(flask=9000,http=8000)
print(services)
{‘http’: 8080, ‘ftp’: 21, ‘ssh’: 22, ‘https’: 443, ‘tomcat’: 8080}
{‘http’: 8000, ‘ftp’: 21, ‘ssh’: 22, ‘https’: 443, ‘tomcat’: 8080, ‘flask’: 9000}
setdefault添加key值
如果key值存在,不做修改
如果key值不存在,添加对应的key-value
services = {
'http':80,
'ftp':21,
'ssh':22
}
services.setdefault('http',9090)
print(services)
services.setdefault('oracle',44575)
print(services)
{‘http’: 80, ‘ftp’: 21, ‘ssh’: 22}
{‘http’: 80, ‘ftp’: 21, ‘ssh’: 22, ‘oracle’: 44575}
四、字典的删除
services = {
'http':80,
'ftp':21,
'ssh':22
}
del services['http'] 删除字典的key-value值
print(services)
{‘ftp’: 21, ‘ssh’: 22}
pop删除指定key的key-value
如果key存在,删除,并返回删除key对应的value
如果不存在,报错
利用pop删除字典的key-value值时,可以将删除掉的值放置一个变量中,可以防止之后再使用
services = {
'http':80,
'ftp':21,
'ssh':22
}
item = services.pop('http')
print(item)
print(services)
80
{‘ftp’: 21, ‘ssh’: 22}
popitem删除最后一个key-value值
services = {
'http':80,
'ftp':21,
'ssh':22
}
item = services.popitem()
print('删除的是:',item)
print(services)
删除的是: (‘ssh’, 22)
{‘http’: 80, ‘ftp’: 21}
clear清空字典内容
services = {
'http':80,
'ftp':21,
'ssh':22
}
services.clear()
print(services)
{}字典内容被清空
五、字典的查看
查看字典的key值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.keys())
dict_keys([‘http’, ‘ftp’, ‘ssh’]) 查看到的key值
查看字典的value值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.values())
dict_values([80, 21, 22])
查看字典的key-value值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.items())
dict_items([(‘http’, 80), (‘ftp’, 21), (‘ssh’, 22)])
查看key的value值
key不存在,默认返回none
key不存在,有default值,则返回default值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.get('http'))
print(services.get('mysql'))
80
None
遍历
services = {
'http':80,
'ftp':21,
'ssh':22
}
#第一种方法实现遍历
for k,v in services.items():
print(k,'--->',v)
#第二种方法实现遍历
for k in services:
print(k,'--->',services[k])
两种输出方法结果相同
http —> 80
ftp —> 21
ssh —> 22
get方法获取指定key对应的value
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.get('https','key not exist'))
print(services.get('http'))
key not exist
80
六、字典的练习
1>
重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.>;
# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;
例:
“hello java hello python”
hello 2
java 1
python 1
s = input('s:')
#1.把每个单词分割处理
s_li = s.split()
print(s_li)
#通过字典存储该单词和其出现的次数
word_dict = {}
"""
依次循环遍历列表
如果列表元素不在字典的key中,将元素作为key 1作为value值
如果列表元素在字典的key中,直接更新元素的value值,在原有的基础上加1
"""
for item in s_li:
if item not in word_dict:
word_dict[item] = 1
else:
word_dict[item] += 1
print(word_dict)
s:hello python hello westos
[‘hello’, ‘python’, ‘hello’, ‘westos’]
{‘hello’: 2, ‘python’: 1, ‘westos’: 1}
2>
数字重复统计:
1) 随机生成1000个整数
2) 数字范围[20,100]
3) 升序输出所有不同的数字及其每个数字的重复次数
import random
word_dict = {}
a=[]
for i in range(1000):
a.append(random.randint(20,100))
a_li = sorted(a)
for item in a_li:
if item not in word_dict:
word_dict[item] = 1
else:
word_dict[item] +=1
print(word_dict)
{20: 11, 21: 8, 22: 10, 23: 11, 24: 19, 25: 10, 26: 10, 27: 7, 28: 10, 29: 15, 30: 11, 31: 12, 32: 12, 33: 15}