[英]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.