[英]Trouble printing out list elements from dictionary
我是一名学生,试图在 Python 中学习编程基础知识。 为了练习,我正在研究 function,它从文件中读取数据,将有问题的两列放在两个列表中,然后将这两个列表分配为字典中的键值对。
我认为我可以很好地完成该任务(尽管它可能是更好和更清洁的方法)。
但是,我的问题是由于某种原因我无法按照我想要的方式打印出两个列表的内容。
我正在读取的数据文件是:
2016 Ukrania
2017 Portugal
2018 Israel
2019 Nederland
2020 Avlyst
2021 Italia
我的代码如下所示:
def ReadEuroVisionInfo(file):
with open(file) as infile:
year = []
country = []
for line in infile:
w = line.strip().split(" ")
year.append(int(w[0]))
country.append(w[1])
return {"Year": year, "Country": country}
euroVision = ReadEuroVisionInfo("songcontest.txt")
# This is where the problem is
for i in euroVision:
for j in i:
print(euroVision[i], euroVision[j])
我希望终端中的 output 是这样的:
2016 Ukrania
2017 Portugal
2018 Israel
2019 Nederland
2020 Avlyst
2021 Italia
我收到的错误消息是:
print(euroVision[i], euroVision[j])
KeyError: 'Y'
有没有人可以帮我解决这个问题?
您有一个带有两个键的dict
,每个值都是一个list
。 你可以这样做
for year, country in zip(d["Year"], d["Country"]):
print(year, country)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.