2015-11-23 95 views
0

所以,的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

试试这个:

choice = random.choice(list(capital_of.keys()))