f1=open("sy9//会员名单.txt","r",encoding="utf8") #代码开始 d={} for line in f1: s=0 name=line.split(",")[0] hy1=line.split(",")[1] hy2=line.split(",")[2] if hy1=="影视黄金会员" and hy2=="体育大众会员": s=297 elif hy1=="影视黄金会员" and hy2=="体育专业会员": s=397 elif hy1=="影视黄金会员" and hy2=="非体育会员": s=199 elif hy1=="非影视会员" and hy2=="非体育会员": s=0 elif hy1=="非影视会员" and hy2=="体育大众会员": s=98 elif hy1=="非影视会员" and hy2=="体育专业会员": s=198 elif hy1=="影视星钻会员" and hy2=="体育大众会员": s=497 elif hy1=="影视星钻会员" and hy2=="体育专业会员": s=597 elif hy1=="影视星钻会员" and hy2=="非体育会员": s=399 d[name]=s for key,value in d.items(): print(key+" "+str(value)) #代码结束 f1.close() 这段代码为什么得到的字典只有最后一项有值
时间: 2023-11-11 18:10:36 浏览: 42
这段代码得到的字典只有最后一项有值是因为你的字典 d 在 for 循环内部被重复定义了,导致每次循环都会重新创建一个空字典,从而丢失之前的数据。所以最终输出的字典只包含最后一次循环得到的数据。
要解决这个问题,你可以将字典 d 的定义放在 for 循环外部,这样就可以在整个循环过程中对同一个字典进行操作。修改后的代码如下:
```python
f1 = open("sy9//会员名单.txt", "r", encoding="utf8")
d = {}
for line in f1:
s = 0
name = line.split(",")[0]
hy1 = line.split(",")[1]
hy2 = line.split(",")[2]
if hy1 == "影视黄金会员" and hy2 == "体育大众会员":
s = 297
elif hy1 == "影视黄金会员" and hy2 == "体育专业会员":
s = 397
elif hy1 == "影视黄金会员" and hy2 == "非体育会员":
s = 199
elif hy1 == "非影视会员" and hy2 == "非体育会员":
s = 0
elif hy1 == "非影视会员" and hy2 == "体育大众会员":
s = 98
elif hy1 == "非影视会员" and hy2 == "体育专业会员":
s = 198
elif hy1 == "影视星钻会员" and hy2 == "体育大众会员":
s = 497
elif hy1 == "影视星钻会员" and hy2 == "体育专业会员":
s = 597
elif hy1 == "影视星钻会员" and hy2 == "非体育会员":
s = 399
d[name] = s
f1.close()
for key, value in d.items():
print(key + " " + str(value))
```
这样就可以正确得到一个包含所有数据的字典了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)