Python: List of dictionary stores only last appended value in every iteration

前端 未结 4 999
一个人的身影
一个人的身影 2021-01-13 17:41

I have this list of dictionary:

MylistOfdict = [{\'Word\': \'surveillance\',
  \'Word No\': 1},
 {\'Word\': \'equivocal\',
  \'Word No\': 2}]
4条回答
  •  被撕碎了的回忆
    2021-01-13 17:53

    When you append a dictionary to a list, a reference to the original object itself is appended. So, you are currently just modifying the existing object's keys and values in each iteration of the inner loop, so the last written value is the only thing which persists.

    To do what you require, you would need to create a new dictionary object in each iteration of the inner loop. For the shown dictionaries in MylistOfdict, a simple dictionary comprehension would work. But if you have more complex dictionaries, use the copy module's deepcopy method.

    MylistOfdict = [{'Word': 'surveillance', 'Word No': 1}, 
                    {'Word': 'equivocal', 'Word No': 2}]
    word_db2 = []
    
    key = 1
    for i in MylistOfdict:
        for j in range(1, 4):
            # Creating a new dictionary object and copying keys and values from i
            new_dict = {k: v for k, v in i.items()}
            new_dict['Card Type'] = 'Type '+str(j)
            new_dict['Card Key'] = key
    
            print(new_dict)
    
            word_db2.append(new_dict)
            key += 1
    

提交回复
热议问题