1.字典的定义
(1)字典的输入输出
字典是一个无序的数据集合,使用print输出字典的时候
通常输出的顺序和定义的顺序是不一致的
注:
zip输出的是一个对象,要输出值要转换类型
字典中元素与元素之间用逗号隔开
users = ['user1','user2']
passwd = ['123','456']
print(zip(users,passwd))
print(list(zip(users,passwd)))
print(dict(zip(users,passwd)))
结果:
<zip object at 0x7f96a3e49788>
[('user1', '123'), ('user2', '456')]
{'user1': '123', 'user2': '456'}
(2)字典:key - value 键值对
value可以是任意数据类型
字典中元素与元素之间用逗号隔开
s = {}
print(type(s))
s = {
'linux':[100,99,88],
'westos':[111,222,333]
}
print (s,type(s))
结果:
<class 'dict'>
{'linux': [100, 99, 88], 'westos': [111, 222, 333]} <class 'dict'>
(3)工厂函数
d = dict()
print (type(d))
d1 = dict(a=1,b=2)
print(d1,type(d1))
结果:
<class 'dict'>
{'a': 1, 'b': 2} <class 'dict'>
(4)字典的嵌套
打印时键对应值
在字典中通过键来调用值
students = {
'2506160223':{
'name':'yjy',
'age':18,
'score':99
},
'2506160213':{
'name':'lry',
'age':18,
'score':99
}
}
print(students['2506160223']['name'])
结果:
yjy
2>所有的key和value值是一样的
students = {
'2506160223':{
'name':'yjy',
'age':18,
'score':99
},
'2506160213':{
'name':'lry',
'age':18,
'score':99
}
}
print(students['2506160223'])
print({}.fromkeys({'2','1'},'123')) #所有的key和value值是一样的
结果:
{'name': 'yjy', 'age': 18, 'score': 99}
{'2': '123', '1': '123'}
3>key的值不一样,value值可以一样
print({}.fromkeys({'2','1','3'},'123'))
结果:
{'1': '123', '3': '123', '2': '123'}
2.字典的特性
(1)字典不支持索引,不支持切片
字典的重复和连接无意义
d = {
'1':'a',
'2':'b'
}
# print(d[0])
# print(d[:])
(2)成员操作符
d = {
'1':'a',
'2':'b'
}
print('1' in d)
结果:
True
(3)for循环,默认遍历字典的key值
for循环里,默认遍历字典的key值
d = {
'1':'a',
'2':'b'
}
for i in d:
print(i)
for i in d: ##遍历字典
print(i,d[i])
结果:
1
2
1 a
2 b
3.字典的增加
(1)增加一个元素
如果key值存在,则更新对应的value值
如果key值不存在,则添加对应key-value
services = {
'http':80,
'ssh':22,
'ftp':21
}
services['mysql'] = 3306
print(services)
services['http'] = 443
print(services)
结果:
{'http': 80, 'ssh': 22, 'ftp': 21, 'mysql': 3306}
{'http': 443, 'ssh': 22, 'ftp': 21, 'mysql': 3306}
(2)添加多个key-value值
services = {
'http':80,
'ssh':22,
'ftp':21
}
services_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
services.update(services_backup)
print(services)
services.update(flask=9000,http=8000)
print(services)
结果:
{'http': 8080, 'ssh': 22, 'ftp': 21, 'https': 443, 'tomcat': 8080}
{'http': 8000, 'ssh': 22, 'ftp': 21, 'https': 443, 'tomcat': 8080, 'flask': 9000}
(3)setdefault添加key值
如果key值存在,不做修改
如果key值不存在,添加对应的key-value
services = {
'http':80,
'ssh':22,
'ftp':21
}
services.setdefault('http',9000)
print(services)
services.setdefault('oracle',44575)
print(services)
结果:
{'http': 80, 'ssh': 22, 'ftp': 21}
{'http': 80, 'ssh': 22, 'ftp': 21, 'oracle': 44575}
4.字典的删除
(1)del随机删除
services = {
'http':80,
'ssh':22,
'ftp':21
}
del services['http']
print(services)
结果:
{'ssh': 22, 'ftp': 21}
(2)pop删除指定key的key-value
如果key存在,删除,并返回删除key对应的value
如果不存在,报错
services = {
'http':80,
'ssh':22,
'ftp':21
}
item = services.pop('http')
print(item)
print(services)
结果:
80
{'ssh': 22, 'ftp': 21}
(3)popitem:删除最后一个key-value值
popitem删除的是键值对
services = {
'http':80,
'ssh':22,
'ftp':21
}
item = services.popitem()
print('删除的是:',item)
print(services)
结果:
删除的是: ('ftp', 21)
{'http': 80, 'ssh': 22}
(4)clear:清空字典内容
services = {
'http':80,
'ssh':22,
'ftp':21
}
services.clear()
print(services)
结果:
{}
5.字典的查看
(1)查看字典的key值
查看字典的value值
查看字典的key-value值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.keys()) ##查看字典的key值
print(services.values()) ##查看字典的value值
print(services.items()) ##查看字典的key-value值
结果:
dict_keys(['http', 'ssh', 'ftp'])
dict_values([80, 22, 21])
dict_items([('http', 80), ('ssh', 22), ('ftp', 21)])
(2)查看key的value值
key不存在,默认返回none
key不存在,有default值,则返回default值
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.get('https',443))
print(services.get('https')) ##key不存在,默认返回none
print(services.get('http')) ##key不存在,有default值,则返回default值
结果:
443
None
80
(3)遍历
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
ssh ----> 22
ftp ----> 21
http ---> 80
ssh ---> 22
ftp ---> 21
(4)get方法获取指定key对应的value
services = {
'http':80,
'ftp':21,
'ssh':22
}
print(services.get('https','key not exist'))
结果:
key not exist
练习1:
重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.>;
- 用户输入一句英文句子;
- 打印出每个单词及其重复的次数;
如: “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)
练习2
数字重复统计:
1) 随机生成1000个整数
2) 数字范围[20,100]
3) 升序输出所有不同的数字及其每个数字的重复次数
import random
num = []
num_dict = {}
for i in range(1000):
num.append(random.randint(20,100))
sort_num = sorted(num)
for n in sort_num:
if n not in num_dict:
num_dict[n] = 1
else:
num_dict[n] += 1
print(num_dict)