Update dictionary keys in a loop in python

I want to update the keys of my dictionary cwith new keys k_new. Although I am referring to various stack overflow problems such as this , it does not update. Please tell me where I am wrong.

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
c = {'apples': 3, 'biscuits and tea': 3, 'oranges and onions': 4}
for k in c:
    splits=k.split()
    k_new= " ".join(lemmatizer.lemmatize(w.lower()) for w in splits)
    c[k_new] = c.pop(k)
print(c)

PS: I also used:

c[k_new] = c[k]
del c[k]

Then i get RuntimeError: dictionary changed size during iteration

Please help me

+4
source share
2 answers

You update the dictionary while it is enumerated:

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
c = {'apples': 3, 'biscuits and tea': 3, 'oranges and onions': 4}
for k in c:  # iterate over c
    splits=k.split()
    k_new= " ".join(lemmatizer.lemmatize(w.lower()) for w in splits)
    c[k_new] = c.pop(k)  # update (two times) c
print(c)

updating a collection while you iterate over it is usually a very bad idea. Most data structures are not designed for this.

However, you can create a new dictionary:

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
c = {'apples': 3, 'biscuits and tea': 3, 'oranges and onions': 4}
c_new = {}
for k in c:
    splits=k.split()
    k_new= " ".join(lemmatizer.lemmatize(w.lower()) for w in splits)
    c_new[k_new] = c[k]
print(c_new)

We can make it more elegant using a dictionary understanding:

{" ".join(lemmatizer.lemmatize(w.lower()) for w in k.split()): v
 for k,v in c.items()}

, - k,v c " ".join(lemmatizer.lemmatize(w.lower()) for w in k.split()), v.

+2

, . , :

for k in list(c):
    ...
+2

Source: https://habr.com/ru/post/1686860/


All Articles