Home > Back-end >  conditional iterating through dictionary
conditional iterating through dictionary

Time:03-26

I'm learning python, and trying to write a code that will present to the user randomly selected word from a pool, and ask him to write the translation for this word. If user translate the word correctly, the word should be deleted from the pool.

Thank you for any help.

dic = {
  "key1": "val1",
  "key2": "val2",
  "key3": "val3"
}

import random

for keys, values in dict(dic).items():
   a = []
   a.append(random.choice(list(dic)))
   translation = input(f"what is the translation for {a}")
   translation.replace("'", "")
   
   if a[0] == translation:
        del dic[keys]

This is the code I write, but even when the condition is occurs, the word is not deleted from the pool.

CodePudding user response:

Don't remove items from a data structure as you're iterating over it.

In this case, observe that you're removing from the dictionary because you don't want to randomly select the same word twice. A better approach (that doesn't require removing elements while iterating) is to transform the dictionary a list of tuples, shuffle that list, and iterate over that list. This lets us select a randomly generated word without having to worry about selecting the same word twice.

Here's a code snippet showing how to implement this:

import random

words = [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]
random.shuffle(words)

for word, translated_word in words:
   user_translation = input(f"what is the translation for {word}?")

   # Remember that .replace() does not modify the original string,
   # so we need to explicitly assign its result!
   user_translation = user_translation.replace("'", "") 
   
   if user_translation == translated_word:
       print('Correct!')
   else:
       print('Incorrect.')
  • Related