views:

87

answers:

4

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},{'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.

A: 

Use

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

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!

Daniel Stutzbach
+1 I'd add the hint "Beware of `matrix = [{'A':0}, ...] * motifWidth` as this creates a list of items referencing the same object.
jellybean
+5  A: 
weightMatrix = [{'A':0,'C':0,'G':0,'T':0} for k in range(motifWidth)]
dan04
+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!-).
Alex Martelli
Awesome, that works. Thanks!
Adrian Randall
A: 

I'm going to assume you want a quick one-liner for this. dan04 has a good solution. You might also want to check this out:

weightMatrix = [{'A':0,'C':0,'G':0,'T':0}] * motifWidth
inspectorG4dget
That's what I mentioned in my comment to dan's answer.
jellybean
Nope, terrible idea -- this will make a list with the **same** dict object referenced-to `motifWidth` times -- *not* a list of (separate) dictionaries like all other answers provide!
Alex Martelli
@jellybean: My apologies. I did not see that post before I posted.@Alex Martelli: I had not known this before. Thanks for giving me this new information
inspectorG4dget
`map(dict, [{'A':0,'C':0,'G':0,'T':0}] * motifWidth)` will work, but is a little bit slower that the list comprehension
gnibbler