2017-11-06 3 views
0

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!

+0

[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

Antwort

1

Sie suchen die Schlüssel sample:

for key in random.sample(dic.keys(), 10): 
+0

Vielen Dank. Dies ist die richtige Lösung. Ich habe nur die 'für den Schlüssel in ...' –

+0

eingestellt, aber ich habe ein Problem. Wenn ich das Programm starte, erscheinen immer noch 2 Großbuchstaben auf der Ausgabe (die nicht zufällig ausgewählt sind). –

+0

@BudDoward Nichts in dem von Ihnen bereitgestellten Code würde das tun. Dieses Problem muss woanders liegen. – glibdud

Verwandte Themen