I have this list of dictionary:
MylistOfdict = [
{'Word': 'surveillance',
'Word No': 1},
{'Word': 'equivocal',
'Word No': 2}]
I want to create a new list of dictionary (word_db2
) that has 3 dictionaries for each dictionary in MylistOfdict
. In addition to key and values of MylistOfdict
, each of those dictionary should have 'Card Type' key with value Type 1, Type 2, Type 3 and 'Card Key' key with incremental value
Code:
word_db2 = []
key = 1
for i in MylistOfdict:
for j in range(1, 4):
i['Card Type'] = 'Type ' + str(j)
i['Card Key'] = key
print(i)
word_db2.append(i)
key += 1
Output:
{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 1', 'Card Key': 1}
{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 2', 'Card Key': 2}
{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3}
{'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 1', 'Card Key': 4}
{'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 2', 'Card Key': 5}
{'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6}
This output is correct, but word_db2
stores only last appended value in every iteration:
[{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3},
{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3},
{'Word': 'surveillance', 'Word No': 1, 'Card Type': 'Type 3', 'Card Key': 3},
{'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6},
{'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6},
{'Word': 'equivocal', 'Word No': 2, 'Card Type': 'Type 3', 'Card Key': 6}]