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

前端 未结 4 1001
一个人的身影
一个人的身影 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 18:05

    Use deepcopy. What's happening is that your append call is just appending a reference to the original object.

    from copy import deepcopy
    
    my_list_of_dict = [{'Word': 'surveillance',
                        'Word No': 1},
                       {'Word': 'equivocal',
                        'Word No': 2}]
    word_db2 = []
    
    key = 1
    for i in my_list_of_dict:
        for j in range(1, 4):
            i['Card Type'] = 'Type ' + str(j)
            i['Card Key'] = key
            print(i)
            word_db2.append(deepcopy(i))
            key += 1
    
    
    for i in word_db2:
        print(i)
    

提交回复
热议问题