I am trying to create a dictionary that has a seq_id and a list of sequences associated with that key. If anyone knows how to resolve this issue that would be much appreciated. Here is my code:
def __init__(self, file):
sequences = {}
with open(file) as handle:
for seq_id, seq in SimpleFastaParser(handle):
if seq_id in sequences:
sequences[seq_id].append(seq)
else:
sequences[seq_id] = seq
self.sequences = sequences
CodePudding user response:
Is it possible you just didn't make it a list (by using square brackets) in the else
scenario?
Suggested code:
def __init__(self, file):
sequences = {}
with open(file) as handle:
for seq_id, seq in SimpleFastaParser(handle):
if seq_id in sequences:
sequences[seq_id].append(seq)
else:
sequences[seq_id] = [seq] ## Change made here
self.sequences = sequences
CodePudding user response:
You'll find setdefault useful here as follows:
def __init__(self, file):
self.sequences = {}
with open(file) as handle:
for seq_id, seq in SimpleFastaParser(handle):
self.sequences.setdefault(seq_id, []).append(seq)
...or...
self.sequences = {seq_id: seq for seq_id, seq in SimpleFastaParser(handle)}