Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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.

like image 755
Adrian Randall Avatar asked Mar 07 '10 20:03

Adrian Randall


People also ask

Can I create an array of dictionaries Python?

A dictionary in Python constitutes a group of elements in the form of key-value pairs. A list can store elements of different types under a common name and at specific indexes. In Python, we can have a list or an array of dictionaries.

Can I make a list of dictionaries Python?

In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type. In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.

How do you create a dictionary array?

Two arrays are required to create a dictionary. One array is used as keys and the other array is used as values. The size of both the arrays should be same, thus making a dictionary with size same as that of the array. Following is the syntax to create a dictionary from two Arrays.


2 Answers

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.

like image 102
user1850980 Avatar answered Sep 23 '22 13:09

user1850980


weightMatrix = [{'A':0,'C':0,'G':0,'T':0} for k in range(motifWidth)] 
like image 37
dan04 Avatar answered Sep 23 '22 13:09

dan04