How can I create an array/list of dictionaries in Python?
I have a dictionary as follows:
{'A':0, 'C':0, 'G':0, 'T':0}
I want to create an array with many dictionaries in it, like this:
[{'A':0, 'C':0, 'G':0, 'T':0}, {'A':0, 'C':0, 'G':0, 'T':0}, {'A':0, 'C':0, 'G':0, 'T':0}, ...]
This is my code:
weightMatrix = []
for k in range(motifWidth):
weightMatrix[k] = {'A':0, 'C':0, 'G':0, 'T':0}
But it’s not working as expected. Can someone give me a hint? Thanks.
(Note: This query is about creating a Python array of dictionaries.)
I’ve worked with this quite a bit, and one way I like to approach it is by using a loop to append dictionaries. For example:
weightMatrix = []
for k in range(motifWidth):
weightMatrix.append({'A': 0, 'C': 0, 'G': 0, 'T': 0})
This solution ensures you’re adding a new dictionary to the weightMatrix
list in every iteration. It’s straightforward and easy to read if you’re just starting out.
Building on that, if you’re comfortable with Python’s more concise syntax, list comprehension is a great alternative:
weightMatrix = [{'A': 0, 'C': 0, 'G': 0, 'T': 0} for _ in range(motifWidth)]
This is a more compact solution that achieves the same result. It’s clean, Pythonic, and eliminates the need for the loop. Personally, I often prefer this for its readability and efficiency in creating the list of dictionaries.
I’ve done a lot of data manipulation like this, and here’s another approach that comes in handy when you need a predefined template dictionary. You can use the * operator along with copy()
to create independent dictionaries:
template = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
weightMatrix = [template.copy() for _ in range(motifWidth)]
The key here is the copy()
method, which ensures that each dictionary in the list is a separate, independent object. This avoids any unintended side effects if you modify one of the dictionaries later. It’s a small tweak but can save a lot of debugging time!