1

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.

2 Answers2

0

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.')
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • Thank you very much for your advice. But what is crucial is that when the condition is met, (when the randomly selected word == to the input of the user) the key-value couple (or tuple in your code) should be deleted. And that is the part I don't succeed at. –  Mar 26 '22 at 01:09
  • Again, in general, it's bad to remove elements from a data structure as you're iterating over it. In this case, we get around this by shuffling the elements and then ignoring the words that the user has already translated. See [here](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) for more discussion on this. – BrokenBenchmark Mar 26 '22 at 01:13
0

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)
Angel
  • 3,617
  • 1
  • 16
  • 13