字典的定义
s = {}
print(s,type(s))
#字典 key-value 键值对
s = {
‘linux’:[100,99,80],
‘python’:[89,90,100]
}
print(s,type(s))
#工厂函数
d = dict()
print(d,type(d))
d = dict(a=1,b=2)
print(d,type(d))
#字典的嵌套
字典的特性
d = {
‘1’:‘a’,
‘2’:‘b’
}
print(d[‘1’])
#字典不支持切片
#成员操作符
print(‘1’ in d)
print(‘1’ not in d)
#for循环 针对key
for key in d:
print(key)
#遍历字典
for key in d:
print(key,d[key])
字典元素的增加
service = {
‘http’:80,
‘ftp’:23,
‘ssh’:22
}
#增加一个元素
#如果key值存在,则更新对应的value值
#如果key值不存在,则添加对应的值
service[‘https’] = 443
print(service)
service[‘ftp’] = 21
print(service)
增加多个元素
先将元素写入一个新字典,再将新字典加入旧字典中
service_backup ={
‘tomcat’:8080,
‘mysql’:3306
}
service.update(service_backup)
print(service)
service.update(dns=53)
print(service)
#如果key值存在,不做修改
#如果key值不存在,则添加对应的值
service.setdefault(‘http’,9090)
print(service)
service.setdefault(‘oracle’,44575)
print(service)
字典元素的删除
service = {
‘http’:80,
‘ftp’:23,
‘ssh’:22,
}
#pop删除指定key对应的value值
#item = service.pop(‘http’)
#print(item)
#print(service)
删除最后一个key-value
a = service.popitem()
print(a)
print(service)
清空字典内容
service.clear()
print(service)
字典内容的查看
service = {
‘http’:80,
‘ftp’:23,
‘ssh’:22,
}
#查看字典中所有的key值
print(service.keys())
#查看字典中所有的value值
print(service.values())
#查看字典中的key-value
print(service.items())
service = {
‘http’:80,
‘ftp’:23,
‘ssh’:22,
}
print(service.get(‘https’,443))
print(service)
练习
#数字重复统计:
1). 随机生成1000个整数;
2). 数字的范围[20, 100],
3). 升序输出所有不同的数字及其每个数字重复的次数;
练习
重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
# 1. 用户输入一句英文句子;
# 2. 打印出每个单词及其重复的次数;