Python-我需要从字典中删除实例吗?

Python-我需要从字典中删除实例吗?,python,dictionary,Python,Dictionary,因此,在我的代码中,我让它从CSV文件中的两行创建一个字典,这非常有效 然而,我将一个问题从字典中随机抽出,以确定字典的长度范围。基本上,我想知道,我是否需要从字典中删除/删除这个实例(问题),因为我使用它是因为它可以再次将其随机输出,还是字典不会将字符串随机输出两次 如果我真的需要移除它,我该怎么做 import csv import random score = 0 # Open file and read rows 0 and 1 into dictionary. capital_of =

因此,在我的代码中,我让它从CSV文件中的两行创建一个字典,这非常有效

然而,我将一个问题从字典中随机抽出,以确定字典的长度范围。基本上,我想知道,我是否需要从字典中删除/删除这个实例(问题),因为我使用它是因为它可以再次将其随机输出,还是字典不会将字符串随机输出两次

如果我真的需要移除它,我该怎么做

import csv
import random
score = 0
# Open file and read rows 0 and 1 into dictionary.
capital_of = dict(csv.reader(open('GeogDatacsv.csv')))
for i in range(len(capital_of)):
    questionCountry = random.choice(list(capital_of.keys()))
    answer = capital_of[country]
    guess = input("What is the capital of %s? " % country)
    print(answer)
    if guess == answer:
        print("Correct, you have scored")
        score +=1
    else: print('Sorry, you have entered an in correct answer')

谢谢

是的,如果不想再次随机选择,您需要删除它


如果您从dict中选择了一个随机键,您可以使用它来获取值,同时删除该项。否则,只需使用
del my_dict[k]

通过将
k
设置为字典的长度,应用字典的项目,您可以在不破坏字典的情况下执行此操作。这将以随机顺序返回字典中的项目列表,然后您可以对其进行迭代

import random

capital_of = {'Australia':'Canberra',
              'England':'London',
              'Indonesia':'Jakarta',
              'Canada':'Ottawa',}

score = 0
for country, capital in random.sample(capital_of.items(), len(capital_of)):
    guess = input("What is the capital of %s? " % country)
    if guess.lower() == capital.lower():
        print("Correct, you have scored")
        score +=1
    else:
        print('Sorry, you have entered an incorrect answer')

print("Score: {}".format(score))
样本输出

What is the capital of Australia? Sydney Sorry, you have entered an incorrect answer What is the capital of England? london Correct, you have scored What is the capital of Indonesia? jakarta Correct, you have scored What is the capital of Canada? toronto Sorry, you have entered an incorrect answer Score: 2 澳大利亚的首都是什么?悉尼 对不起,您输入的答案不正确 英国的首都是什么?伦敦 正确,你得分了 印度尼西亚的首都是什么?雅加达 正确,你得分了 加拿大的首都是什么?多伦多 对不起,您输入的答案不正确 分数:2
那么,您是从字典中随机选取条目,并且不想多次获得相同的条目?那么,是的,你需要从字典中删除它们。你能告诉我,为了使我的代码最有效,我将把问题国家和答案从字典中删除,我将把它编辑到主帖子中。你为什么不在再次寻求帮助之前先自己尝试一下呢,random sample只是从字典中随机选取一个字符串,不会删除/销毁任何内容,但所述字符串只能在字典长度范围内选取一次?此外,我将如何改变字典全文中的问题数量,我通常自己也会尝试一下,但for循环的语法对我来说并不熟悉,非常感谢ThoughtYes,非破坏性和独特性(如链接文档中所述)。您只需更改样本大小即可更改问题数量,即将第二个参数(
k
)调整为
sample()
。使用
len(大写)
会导致所有项目以随机顺序返回。如果您有50个问题,您可以使用
random.sample(大写字母\u of.items(),10)
从50个问题中选择10个随机问题。好的,我明白了,非常感谢您的帮助,非常感谢:)