dict字典练习题

#1、定义工资字典五名员工姓名和公司
salary = {'李广彦':5500,'张超':3800,'王五':5600,'朱纯闯':2000,'焦建强':3400,'张建强':4500,'王琼':4500,'聂守龙':0}

#2、遍历字典
for k,v in salary.items():
print("%s的工资是%d" %(k,v))

#3、查看字典中所有员工的姓名
names = salary.keys()
for i in names:
print(i,end = ",")
print()

#4、查看字典中所有员工的工资
salarys = salary.values()
for i in salarys:
print(i,end=',')
print()

#5、5.查看员工工资总和
salarys = salary.values()
sum = 0
for i in salarys:
sum += i
print("员工的总工资为%d" %(sum))

sum = 0
#6.查看姓张的工资总和
for k,v in salary.items():
if k.startswith('张'):
sum += v
print("姓张的工资总和为%d" %(sum))

#7.查看姓王的员工个数
count = 0
for k in salary.keys():
if k.startswith('王'):
count += 1
print("姓王的员工个数%d" %(count))

#8.把所有员工工资涨1000
for k ,v in salary.items():
salary[k] = salary[k] + 1000
print(salary)

#9.查看5000以上工资的员工有几个
count = 0
for k,v in salary.items():
if salary[k] > 5000:
count += 1
print("5000以上工资的员工有%d个" %count)

for key in salary.keys():
if salary[key] > 5000:
count += 1
print("5000以上工资的员工有%d个" %count)

#10.把王五的工资降薪500
for key in salary.keys():
if key == '王五':
salary[key] = salary[key] - 500
print(salary)


#11.把少于1000的员工开除
print("11=")
dict1 = {'李三':900,'王五':1300,'王二麻':890}
dict2 = {}

for i,j in dict1.items():
list1 = [i,j]
print(list1)
# for i in dict1.keys():
# if dict1[i] < 1000:
# dict2.setdefault(i,dict1[i])
# for i in dict2.keys():
# dict1.pop(i)
# print(dict1)
#12.统计姓王的工资和姓张的工资总和分别多少
sum_wang = 0
sum_zhang = 0
for k in salary.keys():
if k.startswith('张'):
sum_zhang += salary[k]
if k.startswith('王'):
sum_wang += salary[k]
print("姓王的工资和姓张的工资总和分别%d,%d" %(sum_wang,sum_zhang))
#13.新来的员工:马云 工资200000 添加到字典中
salary.setdefault('马云',200000)
print(salary)
#14.把王五员工替换成马化腾
print("14=")
values = salary.get('王五',-1)
salary.setdefault('马化腾',values)
salary.pop('王五')
print(salary)

# 16.把姓王的人员前缀修改为腾讯公司
salary2 = {'微软公司李广彦':5500,'微软公司张超':3800,'微软公司王五':5600,'微软公司朱纯闯':2000,
'微软公司王建强':3400,'微软公司张建强':4500,'腾讯公司王琼':4500,'微软公司聂守龙':0}

# 17.统计微软公司和腾讯公司各多少人
count = 0
count1 = 0
for key in salary2.keys():
if key.startswith('微软公司'):
count += 1
if key.startswith('腾讯公司'):
count1 += 1
print("微软公司有%d,腾讯公司有%d" %(count,count1))
# 18.统计微软公司姓王的平均工资
sum = 0
count = 0
for key in salary2.keys():
if key.startswith("微软公司"):
if key[4] == '王':
sum = sum + salary2[key]
count += 1
pj = sum / count
print(pj)

# 19.统计微软公司和腾讯公司平均工资各多少
sum_tx = 0
sum_wr = 0
count_tx = 0
count_wr = 0
for key in salary2.keys():
if key.startswith("微软公司"):
sum_wr += salary2[key]
count_wr += 1
if key.startswith("腾讯公司"):
sum_tx += salary2[key]
count_tx += 1
pj_tx = sum_tx/count_tx
pj_wr = sum_wr/count_wr
print("微软公司%d,腾讯公司平均工资%d" %(pj_tx,pj_wr))
# 20.把腾讯公司员工全部开除
tx = {}
for key in salary2.keys():
if key.startswith("腾讯公司"):
tx.setdefault(key,salary2[key])
for i in tx.keys():
salary2.pop(i)
print(salary2)

猜你喜欢

转载自www.cnblogs.com/guojie-guojie/p/9229765.html
今日推荐