字典的合并
班级学籍信息统计如下:女生籍贯分布是江苏3人,浙江2人,吉林1人;男生籍贯分布是江苏8人,浙江5人,山东5人,安徽4人,福建2人。编写程序将统计结果合并并输出。
male = {"江苏": 8, "浙江": 5, "山东": 5, "安徽": 4, "福建": 2}
female = {"江苏": 3, "浙江": 2, "吉林": 1}
dic = male.copy() //复制其中的一个空表
for k, v in female.items():
dic[k] = dic.get(k, 0) + v
print(dic)
Python 字典get() 函数返回指定键的值,如果值不在字典中返回默认值。
dict.get(key, default=None)
字典的统计与查找
学生基本信息如表所示。请分别统计男、女生人数,并查找所有年龄超过18岁学生的姓名。
dictStudent = {"黎明": ["男", 19], "杨柳": ["女", 18], "张一帆": ["男", 18], "许可": ["女", 20], "王笑笑": ["女", 19], "陈欣": ["女", 19]}
count = {}
names = []
for k, v in dictStudent.items():
count[v[0]] = count.get(v[0], 0) + 1
if v[1] > 18:
names.append(k)
print("男女生人数为"+str(count))
print("年龄超过18岁的学生姓名为"+str(names))
---------------------------------------------------------------------------------------------------------------------------------+
例二:
班级对“双十一”期间学生消费进行了匿名调查,结果如表所示。编写程序,1、统计每一类消费项目的平均消费金额;2、分别统计男生、女生“双十一”期间消费总额的平均值。
lstExpenses = [{"性别": "女", "书本": 10, "文具": 30, "服饰": 300, "零食": 150, "日用品": 600},
{"性别": "女", "书本": 200, "文具": 10, "服饰": 300, "零食": 300, "日用品": 100},
{"性别": "男", "书本": 200, "文具": 100, "服饰": 100, "零食": 100, "日用品": 200},
{"性别": "男", "书本": 50, "文具": 20, "服饰": 300, "零食": 100, "日用品": 200},
{"性别": "男", "书本": 200, "文具": 50, "服饰": 400, "零食": 100, "日用品": 200},
{"性别": "女", "书本": 100, "文具": 10, "服饰": 5300, "零食": 150, "日用品": 800},
{"性别": "女", "书本": 200, "文具": 100, "服饰": 500, "零食": 300, "日用品": 200},
{"性别": "男", "书本": 300, "文具": 50, "服饰": 0, "零食": 10, "日用品": 50},
{"性别": "男", "书本": 100, "文具": 10, "服饰": 500, "零食": 40, "日用品": 500},
{"性别": "男", "书本": 200, "文具": 50, "服饰": 200, "零食": 100, "日用品": 100}
]
dicTotal = {}
for dic in lstExpenses:
for k, v in dic.items():
if k != "性别":
dicTotal[k] = dicTotal.get(k, 0) + v
for k, v in dicTotal.items():
print("{}:{:.2f}".format(k, v / len(lstExpenses)), ) # 统计各类产品的平均消费额
dicAVG = {}
dicCnt = {}
for dic in lstExpenses:
s = 0
for k, v in dic.items():
if k != "性别":
s = s + v # 计算每一行的消费总额
dicAVG[dic["性别"]] = dicAVG.get(dic["性别"],0)+s # 把相应的总额加到 各类性别中去
dicCnt[dic["性别"]] = dicCnt.get(dic["性别"],0)+1 # 统计男女数量
for sex in ("男","女"):
dicAVG[sex] = dicAVG[sex]/dicCnt[sex]
print(dicAVG)