# Method one
array_a = []
a = {}
for i in range(5):
a = {}
a[str(i)] = i
array_a.append(a)
print(array_a)
# [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}]
# Method two
from copy import deepcopy
array_b = []
b = {}
for i in range(5):
b.clear()
b[str(i)] = i
array_b.append(deepcopy(b))
print(array_b)
# [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}]
I would like to know which one of above is more efficient.
And, if you have a better one, please let me know.
The difference is not relevant. Both need to create a new dict each time. Since the first is clearer, it is preferable over the second method.
My suggestion would be a list comprehension: