一.字典的定义
字典是另一种可变数据类型,可存储任意类型对象。
无序的序列,键值对的输入顺序和在内存中的存储顺序不一致
字典中的数据存储以键值对的方式
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
1.字典的创建
s = {
'linux':[100,99,88],
'python':[190,55,79]
}
print(s,type(s))
{'linux': [100, 99, 88], 'python': [190, 55, 79]} <class 'dict'>
2.工厂函数创建字典
d = dict()
print(d,type(d))
c = dict(a=1,d=2)
print(c,type(c))
{} <class 'dict'>
{'a': 1, 'd': 2} <class 'dict'>
3.空字典的创建
d = dict()
c = {}
print(d,type(d))
print(c,type(c))
{} <class 'dict'>
{} <class 'dict'>
4.字典的嵌套
group = {
'group1':{
'name':'luck',
'age':18,
'score':95
},
'group2':{
'name':'redhat',
'age':17,
'score':87
}
}
print(group)
print(group['group1'])
print(group['group1']['name'])
{'group1': {'name': 'luck', 'age': 18, 'score': 95}, 'group2': {'name': 'redhat', 'age': 17, 'score': 87}}
{'name': 'luck', 'age': 18, 'score': 95}
luck
二.字典的特性
1.通过key值,输出value值
a = {
'name':'westos',
'age' :18
}
print(a['name'])
westos
2.成员操作符,针对key值 判断key值是否为字典中的key
a = {
'name':'westos',
'age' :18
}
print('score' in a)
print('age' not in a)
print('name' in a)
False
False
True
3.for循环遍历,针对key值
a = {
'name':'westos',
'age' :18
}
for key in a:
print(key)
name
age
遍历字典,输出key值及对应的value值
a = {
'name':'westos',
'age' :18
}
for key in a:
print(key,a[key])
name
name westos
age
age 18
三.字典元素的增加
1.增加一个元素 dict[key] = value
>>> service = {
... 'http':80,
... 'ftp':23,
... 'ssh':22
... }
>>> service
{'http': 80, 'ftp': 23, 'ssh': 22}
>>> service['http']=443 ##key值'http'存在
>>> service
{'http': 443, 'ftp': 23, 'ssh': 22}
>>> service['nfs']=56 ##key值‘nfs’不存在
>>> service
{'http': 80, 'ftp': 23, 'ssh': 22, 'https': 443, 'nfs': 56}
注意:当key值存在,则更新对用的value值,key值不存在,则添加新的键值对
2.增加多个key值 dict1.update(dict2)
>>> service
{'http': 443, 'ftp': 23, 'ssh': 22}
>>> service_backup={ ##重新定义一个新字典,里面包含其他元素
... 'tamcat':8080,
... 'mysql':3306
... }
>>> service.update(service_backup) ##将新字典中的元素添加到目标字典中
>>> service
{'http': 443, 'ftp': 23, 'ssh': 22, 'tamcat': 8080, 'mysql': 3306}
3.字典的修改 service.setdefault( )
>>> service
{'http': 443, 'ftp': 23, 'ssh': 22, 'tamcat': 8080, 'mysql': 3306}
>>> service.setdefault('http',8888) ##key值http存在则不做修改
443
>>> service
{'http': 443, 'ftp': 23, 'ssh': 22, 'tamcat': 8080, 'mysql': 3306}
>>> service.setdefault('oracle',4475) ##key值orcle不存在则对原字典做修改
4475
>>> service
{'http': 443, 'ftp': 23, 'ssh': 22, 'tamcat': 8080, 'mysql': 3306, 'oracle': 4475}
注意:如果key值存在:不做修改;如果key值不存在:则添加对应的key-value
四.字典元素的删除
1.del删除
>>> service={
... 'http':80,
... 'ftp':23,
... 'ssh':22
... }
>>> service
{'http': 80, 'ftp': 23, 'ssh': 22}
>>> del service['http']
>>> service
{'ftp': 23, 'ssh': 22}
2.pop()删除 删除key对应的value值
>>> service={
... 'http':80,
... 'ftp':23,
... 'ssh':22,
... 'mysql':2306
... }
>>> service
{'http': 80, 'ftp': 23, 'ssh': 22, 'mysql': 2306}
>>> item = service.pop('http')
>>> item
80
>>> service
{'ftp': 23, 'ssh': 22, 'mysql': 2306}
3.popitem() ##删除字典中最后一对key-value值
>>> service
{'ftp': 23, 'ssh': 22, 'mysql': 2306}
>>> item = service.popitem()
>>> item
('mysql', 2306)
>>> service
{'ftp': 23, 'ssh': 22}
4.clear() ##字典的清空
>>> service
{'ftp': 23, 'ssh': 22}
>>> service.clear()
>>> service
{}
五.字典元素的查看
1.查看key值
>>> service = {
... 'http':80,
... 'ftp':23,
... 'ssh':22
... }
>>> service.keys()
dict_keys(['http', 'ftp', 'ssh'])
>>> service['nfs'] ##当key值不存在则报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'nfs'
2.查看所有的value值
>>> service.values()
dict_values([80, 23, 22])
3.查看字典的key-value值
>>> service.items()
dict_items([('http', 80), ('ftp', 23), ('ssh', 22)])
4.get查看key的value值
>>> service.get('http') ##key值存在返回其value值
80
>>> service.get('https') ##key值不存在返回空
>>> service.get('https','443') ##key值不存在指定返回一个默认值
'443'
六.习题
1.数字重复统计:
1). 随机生成1000个整数;
2). 数字的范围[20, 100],
3). 升序输出所有不同的数字及其每个数字重复的次数;
import random ##获取模块
list=[]
for i in range(1000):
num = random.randint(20, 100)
list.append(num) ##将1000个数字放入列表中
list1=sorted(list) ##对列表进行排序
dict={}
for k in list1: ##将生成的1000个数放入字典中,k做为字典的key值
if k in dict: ##如果key(k)在字典中
dict[k]+=1 ##对应的value值+1
else:
dict[k]=1 ##否则,value值=1
print(dict)
结果测试 key值为排序号的数字,value值为数字出现的个数
{20: 13, 21: 11, 22: 21, 23: 8, 24: 11, 25: 12, 26: 8, 27: 12, 28: 11, 29: 7, 30: 10, 31: 12, 32: 13, 33: 11, 34: 14, 35: 10, 36: 15, 37: 10, 38: 10, 39: 13, 40: 12, 41: 19, 42: 9, 43: 9, 44: 11, 45: 11, 46: 14, 47: 10, 48: 15, 49: 8, 50: 6, 51: 12, 52: 6, 53: 11, 54: 19, 55: 10, 56: 9, 57: 14, 58: 13, 59: 11, 60: 22, 61: 18, 62: 15, 63: 9, 64: 9, 65: 9, 66: 17, 67: 10, 68: 14, 69: 20, 70: 14, 71: 8, 72: 11, 73: 16, 74: 10, 75: 9, 76: 15, 77: 9, 78: 19, 79: 12, 80: 9, 81: 13, 82: 10, 83: 9, 84: 15, 85: 13, 86: 19, 87: 13, 88: 12, 89: 15, 90: 10, 91: 9, 92: 15, 93: 11, 94: 20, 95: 15, 96: 10, 97: 7, 98: 18, 99: 11, 100: 19}
2.重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
用户输入一句英文句子;
打印出每个单词及其重复的次数;
s = input('请输入句子:')
s1 = s.split(' ') ##将但次分割处理成列表形式
dict = {}
for i in s1: ##每个单词作为key值放入字典中
if i in dict:
dict[i]+=1 ##key在字典中,则value+1
else:
dict[i]=1 ##key不再字典中,则value=1`
print(dict)
运行结果:
请输入句子:hello westos hello redhat
{'hello': 2, 'westos': 1, 'redhat': 1}
3.随机生成100个卡号;
卡号以6102009开头, 后面3位依次是 (001, 002, 003, 100),
生成关于银行卡号的字典, 默认每个卡号的初始密码为"redhat";
输出卡号和密码信息, 格式如下:
卡号 密码
6102009001 000000
list=[]
for i in range (100):
s = '6102009%.3d' %(i+1) ##将卡号列举出来
list.append(s) ##卡号放入列表中
dict={}.fromkeys(list,'redhat') ##字典的value值一定
print('卡号\t\t\t\t\t密码')
for k in dict:
print('%s\t\t\t%s' %(k,dict[k])) ##输出字典的key值及value值
输出结果:
卡号 密码
6102009001 redhat
6102009002 redhat
6102009003 redhat
6102009004 redhat
6102009005 redhat
6102009006 redhat
6102009007 redhat
6102009008 redhat
6102009009 redhat
6102009010 redhat
4.求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字
num = int(input('请输入数字:'))
time = int(input('请输入循环次数:'))
NUM = 0
sum = 0
while time>0:
NUM=num+NUM*10 ##aa aaa aaa....表达式
time-=1
sum += NUM
print(sum)
输出结果
请输入数字:2
请输入循环次数:5
24690
5 . 判断101-200之间有多少个素数,并输出所有素数
list=[]
for i in range(101,201):
for k in (2,i):
if i%k==0:
break
else:
list.append(i)
print(list)
输出结果:
[101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199]
6.企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;
利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%;高于100万元时,超过100万元的部分按1%提成;从键盘输入当月利润I,求应发放奖金总数?
方法1:
a = float(input('请输入利润:'))
if 0<a<=10:
b = a*0.1
elif 10<a<=20:
b = 1+(a-10)*0.075
elif 20<a<=40:
b = 1.75+(a-20)*0.05
elif 40<a<=60:
b = 1.85+(a-40)*0.03
elif 60<a<=100:
b = 1.91+(a-60)*0.015
else:
b = 1.97+(a-100)*0.01
print(b)
方法2:
p = float(input('请输入利润:'))
a = 0
dict={100:0.01,60:0.015,40:0.03,20:0.05,10:0.075,0:0.1}
for key in dict:
if key<p:
a+=(p-key)*dict[key]
p = key
print(a)
print(dict)
请输入利润:11
1.075
{100: 0.01, 60: 0.015, 40: 0.03, 20: 0.05, 10: 0.075, 0: 0.1}
7.累加和类型程序:
(1)求f=1+2+…+9【很简单的问题】
sum = 0
for i in range(1,10):
sum+=i
print(sum)
(2)求f=1-2+3-4+…+9【在(一)的基础上,学习如何一正一负地累加】
sum = 0
sum1 = 0
sum2 = 0
for i in range(1,10,2):
sum1+=i
for i in range(2,10,2):
sum2+=i
sum = sum1-sum2
print(sum)
(3)求f=1-1/2+1/3-1/4+…+1/9【在(二)的基础上,被加数成了自然数的倒数】
dict = {}.fromkeys(range(1,10),-1)
f = 0
for i in dict:
f +=i**dict[i]*dict[i]**(i+1)
print(f)
(4)求f=1!-2!+3!-4!+…+9!【在(二)的基础上,被加数成了自然数的阶乘】
dict = {}.fromkeys(range(1,4),-1)
f = 0
for i in dict:
m = 1
for k in range(1,i+1):
m=m*k
f +=m*dict[i]**(i+1)
print(f)