I am trying to create a dictionary through a comprehension but I have to use keys from a specific range of numbers and values from a predefined list:
pssmList=[]
for column in columns:
pssmList.append(collections.Counter(column))
pssmDict = {key:value for key in range(0, len(pssmList)) for value in
pssmList}
Now, I know that the Counter object is a type of dict but I need those objects inside of pssmDict assigned to keys from a numerical range specified above and all I get is the last element in pssmList repeated over and over again, although each line should be different (and yes, I checked the list and it really contains different records):
Key Number
0 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
1 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
2 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
3 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
4 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
5 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
Desired output:
Key Number
0 Counter({'V': 14, 'L': 2, 'A': 1})
1 Counter({'D': 17})
2 Counter({'F': 17})
3 Counter({'S': 8, 'W': 5, 'Y': 3, 'T': 1})
4 Counter({'A': 17})
5 Counter({'T': 8, 'E': 4, 'P': 2, 'V': 1, 'S': 1, 'D': 1})
Does anyone have any idea why this does not work? I've searched StackOverflow for similar problems but either I'm bad at searching or such questions haven't appeared.
Please excuse me if my mistake is trivial, I'm in my third month of learning Python (and coding altogether).
Zip the two sources together:
pssmDict = {key: value for key, value in zip(range(0, len(pssmList)), pssmList)}
However, in this case, you can simply use enumerate
to generate the keys.
pssmDict = {key: value for key, value in enumerate(pssmList)}
The results of zip
and enumerate
are suitable for passing directly to dict
; no need for a dictionary comprehension:
pssmDict = dict(enumerate(pssmList))