简体   繁体   中英

Trouble printing out list elements from dictionary

I am a student trying to learn the basics of programming in Python. For the sake of practice, I am working on a function that reads data from a file, put the two columns in question in two lists, and then assigns the two lists as a key-value pair in a dictionary.

I think I manage that task fairly OK (although it is probably better and cleaner ways of doing this).

However, my problem is that I for some reason don't manage to print out the contents for the two lists the way I want.

The data file I am reading from is:

2016 Ukrania
2017 Portugal
2018 Israel
2019 Nederland
2020 Avlyst
2021 Italia

My code looks like:

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])

I want the output in the terminal to be like this:

2016 Ukrania
2017 Portugal
2018 Israel
2019 Nederland
2020 Avlyst
2021 Italia

The error message I'm getting is:

    print(euroVision[i], euroVision[j])
KeyError: 'Y'

Is there anyone who can help me fix this?

You have a dict with two keys, each value is a list . You can do like this

for year, country in zip(d["Year"], d["Country"]):
    print(year, country)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM