首页 新闻 会员 周边 捐助

python相同键的两个字典合并

0
悬赏园豆:20 [已解决问题] 解决于 2023-03-16 10:06

这里有学生的学号和姓名字典: {100: "王一", 101:"李二", 102:"张三", 103:"钱四", 104:"孙五", 105:"马六"}

学生的学号和BMI指数字典: {102: 25.8, 100:18, 105:21, 104:22}

编程构造一个字典,key是学号, 比如102; value是姓名和BMI组成的tuple,比如("张三", 25.8)。没有BMI的学生数据忽略。

num_name = {100: "王一", 101:"李二", 102:"张三", 103:"钱四", 104:"孙五", 105:"马六"}
num_BMI = {102: 25.8, 100:18, 105:21, 104:22}
for i in num_name:
for j in num_BMI:
if i == j:
new = {i:list(zip(num_name[i], num_BMI[j]))}
print(new)

TypeError Traceback (most recent call last)
<ipython-input-3-15bb52b0da0f> in <module>
4 for j in num_BMI:
5 if i == j:
----> 6 new = {i:list(zip(num_name[i], num_BMI[j]))}
7 print(new)

TypeError: 'int' object is not iterable

想学习的渣渣的主页 想学习的渣渣 | 初学一级 | 园豆:184
提问于:2023-03-16 08:23
< >
分享
最佳答案
0

num_name = {100: "王一", 101: "李二", 102: "张三", 103: "钱四", 104: "孙五", 105: "马六"}
num_BMI = {102: 25.8, 100: 18, 105: 21, 104: 22}
new = {}
for i in num_name:
for j in num_BMI:
if i == j:
new[i] = (num_name[i],num_BMI[i])
print(new)

收获园豆:20
KikN | 初学一级 |园豆:38 | 2023-03-16 09:57

谢谢大佬!!!!!

想学习的渣渣 | 园豆:184 (初学一级) | 2023-03-16 10:07

@想学习的渣渣: 加油,学习使你快乐

KikN | 园豆:38 (初学一级) | 2023-03-23 09:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册