简体   繁体   English

无法从字典中打印出列表元素

[英]Trouble printing out list elements from dictionary

I am a student trying to learn the basics of programming in Python.我是一名学生,试图在 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.为了练习,我正在研究 function,它从文件中读取数据,将有问题的两列放在两个列表中,然后将这两个列表分配为字典中的键值对。

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:我希望终端中的 output 是这样的:

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 .您有一个带有两个键的dict ,每个值都是一个list You can do like this你可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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