[英]Edit dictionary in a loop and append a list
I am trying to edit a base dictionary in a loop and then append a list that will contain all of the edited dictionaries.我正在尝试在循环中编辑基本字典,然后 append 将包含所有已编辑字典的列表。 No matter what I've tried, I cannot get the list to append correctly, however I can print the edited dictionary in the loop and it works fine.
无论我尝试了什么,我都无法正确获取 append 的列表,但是我可以在循环中打印编辑过的字典并且它工作正常。
What I've tried:我试过的:
someList = []
for key, value in someDict.items():
k=0
while k < someVal:
someDict["someKey"] = "someValue"+str(k)
someList.append(someDict)
k=k+1
print(someList)
In addition to this, I have tried putting the while
loop on the outside and the for
loop inside it - no luck either.除此之外,我还尝试将
while
循环放在外面,将for
循环放在里面 - 也没有运气。 I have also tried the update method for the dictionary, but it leads to the same result.我也尝试过字典的更新方法,但结果相同。
Edit - suppose the dictionary is {"key1":"value1"} and I am trying to update it to "valueN" where N is the current iteration of the loop.编辑 - 假设字典是 {"key1":"value1"} 并且我正在尝试将其更新为 "valueN",其中 N 是循环的当前迭代。 When I do this, someList consists of a bunch of copies of the same dictionary, all with the last edited value.
当我这样做时, someList 由同一个字典的一堆副本组成,所有这些副本都具有最后编辑的值。
I found a solution:我找到了一个解决方案:
someList.append(someDict.copy())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.