我想用它的新键 c
更新我的字典 k_new
的键。即使我指的是 this 等不同的堆栈溢出问题,它也不会更新。请告诉我哪里出错了。
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:我也用过:
c[k_new] = c[k]
del c[k]
然后我得到
RuntimeError: dictionary changed size during iteration
请帮我
最佳答案
迭代时更新字典:
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)
在迭代时更新集合通常是一个非常糟糕的主意。大多数数据结构都不是为了处理这个问题而设计的。
但是,您可以构建一个新字典:
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)
我们可以通过使用字典理解使这更优雅:
{" ".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
。关于python - 在python中循环更新字典键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46560248/