【问题标题】:Finding a dictionary number x in a list of dictionaries在字典列表中查找字典编号 x
【发布时间】:2019-10-18 19:36:25
【问题描述】:

我正在尝试通过使用循环在字典列表中查找特定字典。但是我收到一条错误消息: KeyError: 1

def EU():
    wrong = 0
    correct = 0
    for country in eu:
        ans = input("what is the capital of " + country[0][1] + ": ")
        str.lower(ans)
        if ans == country[1][1]:
            print("CORRECT")
            correct = correct + 1
        else:
            print("WRONG. It is: " + country[1][1])
            wrong = wrong + 1

    print("Correct: " + str(correct))
    print("wrong: " + str(wrong))
    print("You got " + str(correct) + " out of 25")

#finding the data from a .csv file

nl = {'newline': ''}
mode = 'r'
if sys.version_info < (3, 0):
    nl.pop('newline', None)
    mode = 'rb'
with open('Europe_Capitals.csv', mode, **nl) as fp:
    reader = csv.reader(fp, delimiter=',', quotechar='"')
    # next(reader, None)  # skip the headers
    dr = [row for row in reader]

europe = []

for y in range(0, 51):
    a = {
            "Country" : dr[y][0],
            "Capital" : dr[y][1]
        },
    #print(a)
    if y == 51:
        a = {
            "Country" : dr[y][0],
            "Capital" : dr[y][1]
            }
    europe.append(a)

该程序旨在循环遍历欧洲的首都并询问我,但我得到的是“国家的首都是什么”,现在我只收到一条错误消息,指出 KeyError: 1

【问题讨论】:

  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。你已经包含了多余的系统代码,并省略了你的数据结构。不要读取文件;只需分配您的目录。
  • 我们可以看到Europe_Capitals.csv中的数据样本吗?
  • if y == 51: 这永远不会是真的,因为range(0, 51) 停在50
  • 你为什么还需要那个,因为它和a之前的分配一样?

标签: python list csv


【解决方案1】:

本节

a = {
        "Country" : dr[y][0],
        "Capital" : dr[y][1]
     },    # <-- note the comma

正在创建一个元组(dict, None)

所以当你有

for country in eu:
   ...

country 是相同的形式,一个元组。所以country[0] 给了你字典但是它没有键1 所以它抛出了键错误

你应该去掉创建a(上图)末尾的逗号。

然后,要获取国家/地区名称,您将使用 country["Country"] 并获取首都使用 country["Capital"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多