75

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.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Adrian Randall
  • 751
  • 1
  • 5
  • 3
  • Does this answer your question? [Create list of single item repeated N times](https://stackoverflow.com/questions/3459098/create-list-of-single-item-repeated-n-times) – Georgy Oct 31 '20 at 12:40

8 Answers8

76

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.

user1850980
  • 991
  • 1
  • 10
  • 15
32
weightMatrix = [{'A':0,'C':0,'G':0,'T':0} for k in range(motifWidth)]
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
dan04
  • 87,747
  • 23
  • 163
  • 198
  • 3
    +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 Mar 07 '10 at 20:21
  • 2
    @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. – dan04 Apr 16 '19 at 19:18
21

Use

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
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.)

Clem Wang
  • 689
  • 8
  • 14
9

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
Avinash
  • 2,003
  • 2
  • 17
  • 15
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!

Daniel Stutzbach
  • 74,198
  • 17
  • 88
  • 77
  • 3
    +1 I'd add the hint "Beware of `matrix = [{'A':0}, ...] * motifWidth` as this creates a list of items referencing the same object. – Johannes Charra Mar 07 '10 at 20:18
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}]
""")
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
-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'})
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
  • 11
    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. – Tim Pietzcker Dec 08 '14 at 10:26