Paolo Lorenzini
Paolo Lorenzini

Reputation: 725

Iterate over values and keys in multiple dictionaries stored in list

I have a dictionary

selection60 = {"A":2, "T":2, "G":3, "C":3}
sseq60=[]
for k in selection60:
    sseq60 = sseq60 + [k] * int(selection60[k])
    random.shuffle(sseq60)

Output from this code:

sseq60=['C', 'G', 'T', 'C', 'C', 'A', 'G', 'G', 'T', 'A']

I know how to access the values for each key with the for loop. Now, I have a list of dictionaries:

[{'A': 2, 'T': 2, 'G': 3, 'C': 3}, {'A': 3, 'T': 3, 'G': 3, 'C': 1}]

How, to iterate over each dictionary in the list and do the same? Ultimately, I would like To do the same and create a list of list

Expected output:

[['C', 'G', 'T', 'C', 'C', 'A', 'G', 'G', 'T', 'A']['C', 'G', 'T', 'T', 'T', 'A', 'G', 'G', 'A', 'A']]

Upvotes: 1

Views: 133

Answers (2)

quantotto
quantotto

Reputation: 31

You could define your code snippet as a function, something like:

from typing import List, Dict

def randomize_dna_seq(d: Dict) -> List[str]:
    selection60 = {"A":20, "T":20, "G":30, "C":30}
    sseq60=[]
    for k in selection60:
        sseq60 = sseq60 + [k] * int(selection60[k])
        random.shuffle(sseq60)
    return sseq60

and then, when you have a list of such dicts, you could use map to create a list of lists:

seq_dicts = [{'A': 25.0, 'T': 25.0, 'G': 24, 'C': 26}, {'A': 25.0, 'T': 25.0, 'G': 30, 'C': 20}, {'A': 23.0, 'T': 23.0, 'G': 34, 'C': 20}]
randomized_seqs = list(map(randomize_dna_seq, seq_dicts))

Upvotes: 1

Sabareesh
Sabareesh

Reputation: 751

I think this is what you want:

selection60 = [{'A': 25.0, 'T': 25.0, 'G': 24, 'C': 26}, {'A': 25.0, 'T': 25.0, 
                'G': 30, 'C': 20}, {'A': 23.0, 'T': 23.0, 'G': 34, 'C': 20}]
sseq60_list = []
for selection_dict in selection60:
    sseq60 = []
    for k, v in selection_dict.items():
        sseq60 = sseq60 + [k] * int(v)
        random.shuffle(sseq60)
    sseq60_list.append(sseq60)

Upvotes: 2

Related Questions