I'm trying to write a function that returns an array of the elements of the longest length. I'm not looking for the longest element, but the longest element s.
The approach I've taken is to create a dictionary of arrays where the key is the length and the value is an array of elements of the length indicated by the key.
This is the code I've come up with
#initialise the dictionary
longest = {}
#this keeps track of the greatest length
longestNum = 0
for seq in proteinSeq:
if len(seq) >= longestNum:
longestNum = len(seq)
#check to see if the dic key exists
#if not initialise it
try:
longest[longestNum].append(seq)
except NameError:
longest[longestNum] = []
longest[longestNum].append(seq)
return longest[longestNum]
It gives me a KeyError: 6 at the first longest[longestNum].append(seq)...
Can someone help me find what the problem here is?