1

I have a series of genes that I would like to associate with a list of properties and a color:

gene_A_color = red gene_B_color = blue gene_A_property = ['a','b','c'] gene_B_property = ['d','e','f'] 

For the purpose of plotting I would like to create a dictionary where I can use the property value as the key to get either the color or the gene as follows:

#lookup dictionary {'a': ['red', 'gene_A'] 'b': ['red', 'gene_A'] 'c': ['red', 'gene_A'] 'd': ['blue' 'gene_B'] 'e': ['blue' 'gene_B'] 'f': ['blue' 'gene_B']} lookup[a][0] = red lookup[a][1] = gene_A 

I started off as so but can only invert the list if I lose the gene name:

lookup_dict = defaultdict(list) lookup_dict['red'] = ['a','b','c'] lookup_dict['blue'] = ['d','e','f'] inverted = defaultdict(list) for k, v in lookup_dict.items(): inverted[v].append( k ) #inverted {'a': 'red' 'b': 'red' 'c': 'red' 'd': 'blue' 'e': 'blue' 'f': 'blue' } 

suggestions?

2 Answers 2

6

You already have everything you need, an association of genes with properties. Everything else just kind of works itself out.

Why not use a class to represent the genes?

class Gene(object): def __init__(self, color, properties): self.color = color self.properties = properties geneA = Gene('red', ['a', 'b', 'c']) geneB = Gene('blue', ['d', 'e', 'f']) genes = [geneA, geneB] inverted = {} for gene in genes: for prop in gene.properties: inverted[prop] = gene.color 
Sign up to request clarification or add additional context in comments.

1 Comment

good call. i could make the class also have gene.name and do inverted[prop] = [gene.color, gene.name] thanks!
1

In case you just want a couple of simple statements to do this:

>>> gene_A_property = ['a','b','c'] >>> gene_B_property = ['d','e','f'] >>> ld={k:['red','gene_A'] for k in gene_A_property} >>> ld.update({k:['blue','gene_B'] for k in gene_B_property}) >>> ld { 'a': ['red', 'gene_A'], 'c': ['red', 'gene_A'], 'b': ['red', 'gene_A'], 'e': ['blue', 'gene_B'], 'd': ['blue', 'gene_B'], 'f': ['blue', 'gene_B'] } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.