In meiner .csv-Datei habe ich insgesamt 12 Länder (mit 12 Großbuchstaben). Ich möchte jedoch zufällig 10 dieser 12 Länder auswählen.Wie 10 Elemente aus dem Wörterbuch csv nach dem Zufallsprinzip ausgewählt werden?
Ich habe von stackoverflow Ressourcen einige einzelne oder Paar Auswahl gefunden, aber nicht zufällig 10 Elemente aus einem Wörterbuch auswählen. Wie kann ich das machen?
Dies ist der relevante Code, den ich für eine Länder- und Hauptstädteprüfung habe, bei der der Benutzer das Kapital in das angeforderte Land eingibt und eine korrekte oder falsche Antwort ausgibt.
#Defining the function of reading .csv file from path into dictionary
def readCsvIntoDictionary(path):
dic = {}
with open(path, 'r', newline='') as f:
reader = csv.reader(f)
for row in reader:
dic[row[0]] = row[1];
return dic;
count = 0;
# for loop with key variable definition in dic
for key in dic:
# ans variable defined for user input
ans = input('What is the capital of ' + key + '?\n')
# User can input lower and upper answers
if(ans.lower() == dic[key].lower()):
# key lookup in dic (dictionary) if answer is correct at end of the loop
dic[key] = 'Correct! ' + dic[key] + ' is the capital of ' + key;
count = count + 1;
else:
# key lookup in dic (dictionary) if answer is incorrect at end of the loop
dic[key] = 'Wrong! \'' + ans + '\' is not the capital of ' + key + ', it\'s ' + dic[key];
Vielen Dank!
[random.sample()] (https://docs.python.org/3/library/random.html#random.sample) könnte Arbeite für dich. 'random.sample (liste (dic), 10)' gibt Ihnen 10 zufällige Schlüssel – Felk