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

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

    Let's review the loop body logic step by step:

    1. take one of the dicts
    2. modify it
    3. append it to the end of the list

    So the key point you missed is that you modify and append the same object that was selected on the first step. And at the end of the snippet word_db2 contains six object refs, but only two unique. As a result, the output shows similar rows.

    You can make a shallow copy of a dict before modifying and appending it:

    for j in range(1, 4):
        i = dict(i)
        i['Card Type'] = 'Type '+str(j)
        i['Card Key'] = key
        print(i)
    
        word_db2.append(i)
        key += 1
    

    As further note, if the dict contains other mutable objects like nested dicts, you should make a deep copy:

    import copy
    old_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
    new_dict = copy.deepcopy(old_dict)
    old_dict['a'][1] = 7
    new_dict['a'][1] # 2
    

提交回复
热议问题