'how to read file into dictionary (seq_id and seq)?
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:
class Oragnise:
def __init__(self, file):
with open(file) as handle:
self.sequences = {seq_id: seq for seq_id, seq in SimpleFastaParser(handle)}
def get_variant(self, variant=None):
if variant is None:
return list(self.sequences.values())
return self.sequences.get(variant)
def get_num(self, variant=None):
if variant is None:
return {key: len(value) for key, value in self.sequences.items()}
return len(self.sequences.get(variant))
Solution 1:[1]
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
Solution 2:[2]
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)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eccentricOrange |
| Solution 2 |
