79

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, as follows:

[{'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 of course it isn't working. Can someone give me a hint? Thanks.

2

8 Answers 8

80

This is how I did it and it works:

dictlist = [dict() for x in range(n)]

It gives you a list of n empty dictionaries.

Sign up to request clarification or add additional context in comments.

4 Comments

that wasn't what he asked... and it was already answered 2 years ago
Yes, he should have asked a different question.
The BEST solution ever. Works for Python3.
Worked great. Not sure why the poster didn't accept your answer. Of course, not a direct answer, but could easily be tailored.
34
weightMatrix = [{'A':0,'C':0,'G':0,'T':0} for k in range(motifWidth)]

2 Comments

+1 because list comprehension is the way to go (more readable, elegant and concise than a loop of .append calls), even though the k in motifWidth in the original answer was an obvious, horrible bug (I've edited the Answer to fix that!-).
@devon: No, they aren't. Note, for example, that if you run weightMatrix[0]['A'] += 1, then weightMatrix[1] still has all 0's in its dictionary values. The list comprehension works differently from [{'A':0,'C':0,'G':0,'T':0}] * motifWidth, which would create multiple copies of the same dict object.
22

Use

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

Comments

12

Minor variation to user1850980's answer (for the question "How to initialize a list of empty dictionaries") using list constructor:

dictlistGOOD = list( {} for i in xrange(listsize) )

I found out to my chagrin, this does NOT work:

dictlistFAIL = [{}] * listsize  # FAIL!

as it creates a list of references to the same empty dictionary, so that if you update one dictionary in the list, all the other references get updated too.

Try these updates to see the difference:

dictlistGOOD[0]["key"] = "value"
dictlistFAIL[0]["key"] = "value"

(I was actually looking for user1850980's answer to the question asked, so his/her answer was helpful.)

Comments

10

Try this:

lst = []
##use append to add items to the list.

lst.append({'A':0,'C':0,'G':0,'T':0})
lst.append({'A':1,'C':1,'G':1,'T':1})

##if u need to add n no of items to the list, use range with append:
for i in range(n):
    lst.append({'A':0,'C':0,'G':0,'T':0})

print lst

Comments

4

I assume that motifWidth contains an integer.

In Python, lists do not change size unless you tell them to. Hence, Python throws an exception when you try to change an element that isn't there. I believe you want:

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

For what it's worth, when asking questions in the future, it would help if you included the stack trace showing the error that you're getting rather than just saying "it isn't working". That would help us directly figure out the cause of the problem, rather than trying to puzzle it out from your code.

Hope that helps!

1 Comment

+1 I'd add the hint "Beware of matrix = [{'A':0}, ...] * motifWidth as this creates a list of items referencing the same object.
0

You can use import json, e.g.

weightMatrix = json.loads("""
[{"A":0,"C":0,"G":0,"T":0},
 {"A":0,"C":0,"G":0,"T":0},
 {"A":0,"C":0,"G":0,"T":0}]
""")

Comments

-8

Dictionary:

dict = {'a':'a','b':'b','c':'c'}

array of dictionary

arr = (dict,dict,dict)
arr
({'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'})

1 Comment

First, you should never use dict as a variable name, and second, you're creating a tuple (not a list) that contains the same dictionary three times, so every change you make to one of them affects all the others.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.