[英]Update dictionary keys in a loop in python
我想用新密鑰k_new
更新我的字典c
鍵。 雖然我指的是不同的堆棧溢出的問題,如這樣它不會得到更新。 請告訴我哪里弄錯了。
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())
添加一個鍵" ".join(lemmatizer.lemmatize(w.lower()) for w in k.split())
我們與聯想的價值v
。
在字典更改時迭代字典可能會產生效果,因為您正在使用對鍵的實時引用。 只需從關鍵視圖中列出一個列表,它就會起作用:
for k in list(c):
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.