2015-11-23 128 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()))