-1

In this code, I'm importing a dictionnary (dict_nombre) from another Python file(dictnombre.py).

The imported dictionnary is passed in the variable "dict".

Later the code is deleting the key and values of "dict". Until here, everything is working as expected.

But when I click after that on the button "bouton_chiffre", "dict" remains empty although the function should pass again the imported dictionnary to "dict"

dict_nombre in the file dictnombre.py:

dict_nombre={'un (chiffre)':'yi-',
'deux':'èr',
'trois':'sa-n',
'quatre':'sì',
'cinq':'wû',
'six':'liù',
'sept':'qî',
'huit':'ba-',
'neuf (chiffre)':'jiû',
'dix':'shí'
}

The code:

...
import dictnombre
...

def nombres():
    global dict
    dict=dictnombre.dict_nombre
...
    del dict[key_aleatoire]
...
bouton_chiffre=Button(cadre_bouton,text="Nombres seulement",width=15,height=1,bg="blue",bd=5, command=nombres)
bouton_chiffre.pack(side=LEFT)

SOLUTION (29.03.2023):

dict_copy=dictnombre.dict_nombre.copy()

Thanks everyone for the help !

Meriole
  • 127
  • 8
  • 7
    You're destructively changing the dictionary. You only have one dictionary, so any changes you make to it are permanent. If you need a copy of it that you can change without affecting the original, then copy it. Also, don't use `dict` as a variable name, since that will mask the builtin `dict`. – Tom Karzes Mar 28 '23 at 22:08
  • 1
    Python does not copy objects on assignment, so `dict=dictnombre.dict_nombre` means the **same object** each time (since `dictnombre` always means the same module object). Please see the linked duplicate for details. – Karl Knechtel Mar 28 '23 at 23:06
  • 1
    As an aside, [please do not use `dict` as a name for the dictionary](https://stackoverflow.com/questions/20125172). – Karl Knechtel Mar 28 '23 at 23:07

1 Answers1

1

In your code, dict and dictnombre.dict_nombre refer to the exact same object. so when you remove a key from dict it is removing it from the same dictionary that dictnombre.dict_nombre is referencing. That is why once you delete, its gone for good.

LhasaDad
  • 1,786
  • 1
  • 12
  • 19