Python - 使用字典

时间:2015-11-23 19:31:55

标签: python csv

所以,

我使用的是Python 3.4.2,我有这段代码:

import csv
import random

filename = input("Please enter the name of your file: ")

# Open file and read rows 0 and 1 into dictionary.
capital_of = dict(csv.reader(open(filename)))

# Randomly select a country from the dictionary
choice = random.choice(capital_of.keys())

# The correct capital corresponds to the dictionary entry for the country
answer = capital_of[choice]

# Take a guess from the user
guess = input("What is the capital of %s? " % choice)

# If it's right, let the user know
if guess == answer:
  print("Right-o!")
# Otherwise, do what you want to do.

此代码作为上一个问题的解决方案提供给我,但在输入我的CSV文件的名称后,我收到此错误:

TypeError: 'dict_keys' object does not support indexing

有人知道解决这个问题吗?

由于

0 个答案:

没有答案