如何让字典打印出随机密钥

时间:2017-11-12 19:16:46

标签: python dictionary

file = open(selection, 'r')
dictionary = {}
with file as f:
    for line in f:
        items = line.split(',')
        key, values = items[0], items[1:]
        dictionary[key] = values

n= int(input("How many words would you like to be tested on: "))
while n > length:
    print("Invalid. There are only" ,length, "entries")
    n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")


for i in range(n):
    while len(dictionary)>0:
        choice = random.shuffle(list(dictionary.keys()))
        correctAnswer = dictionary.get(choice)
        print("English: ",choice)
        answer = input("Spanish: ")
        if answer.lower() == correctAnswer:
            print("Correct!\n")
            del dictionary[choice]
        else:
            print("Incorrect")
            wrongAnswers.append(choice)
        break
print("\nYou missed", len(wrongAnswers), "words\n")

嗨,我正在尝试在python上创建一个词汇测试,但是当我运行代码时,它只打印出“无”而不是打印出来的密钥。 如何打印随机密钥,我该怎么办?

1 个答案:

答案 0 :(得分:3)

您可以使用random.choice而不是shuffle。

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

shuffle会更改您发送到函数中的列表,并且由于您没有保存对该列表的引用,因此您无法获得任何内容。此外,它只生成该列表的混洗版本而不是单个值。

alist = [1,2,3,4,5,6]
random.shuffle(alist)
print(alist)

>> [2, 5, 6, 4, 3, 1]