'conditional iterating through dictionary

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.



Solution 1:[1]

As BrokenBenchmark say, don't remove elements on loops !!!

Do a copy of the keys, and remove form the original dictionary.

Here is a corrected version of your code:

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

import random

keys = list(dic.copy())
random.shuffle(keys)
for key in keys:
  translation = input(f"what is the translation for {key}: ")
  translation.replace("'", "")
   
  if dic[key] == translation:
      del dic[key]
        
print(dic)

Solution 2:[2]

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.')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Angel
Solution 2 BrokenBenchmark