Running into some syntax problems trying to generate a nested dictionary. My code attempt is the following:
from collections import defaultdict
count = 0
target_dict = defaultdict(dict)
for alignment in item.alignments:
for hsp in alignment.hsps:
if hsp.expect < E_VALUE_THRESH:
try:
target_dict['Entry'+'_'+str(count)]['Sequence'+'_'+str(count)] = alignment.title,/
['Length'+('_'+str(count))] = alignment.length,/
['Score'+('_'+str(count))] == hsp.score/
['Hsp_query'+('_'+str(count))] == ("{}".format(hsp.query[0:90]))/
['Hsp_match'+('_'+str(count))] == ("{}".format(hsp.match[0:90]))/
['Hsp_sbjct'+('_'+str(count))] == ("{}".format(hsp.sbjct[0:90]))
except KeyError as e:
print('exception missing key', e)
count+=1
Gives kindof what I'm looking for (but when trying to add additional key:value pairs inside the entry key I get syntax errors:
target_dict['Entry'+'_'+str(count)]['Sequence'+'_'+str(count)] = alignment.title,/
^
SyntaxError: invalid syntax
Desired output is:
{'Entry_0': {'Sequence_0': 'gi|1219041180|ref|XM_021875076.1| PREDICTED: Chenopodium quinoa cold-regulated 413 plasma membrane,
'Length_0': 1173,
'Score_0': 482.0,
'Hsp_query_0': 'ACAGAAAATGGGGAGAGAAATGAAGTACTTGGCCATGAAAACTGATCAATTGGCCGTGGCTAATATGATCGATTCCGATATCAATGAGCT',
'Hsp_match_0': '|| ||||||||| |||| | |||| || |||| |||| | |||| ||| | |||| ||| ||| ||||| | ||||| |||||||||||',
'Hsp_sbjct_0': 'ACCGAAAATGGGCAGAGGAGTGAATTATATGGCAATGACACCTGAGCAACTAGCCGCGGCCAATTTGATCAACTCCGACATCAATGAGCT',
How can I make this nested dictionary? Any help on how I'm going wrong with syntax would be much appreciated thank you!
I think you are trying to "add to the [inner] dictionary" incorrectly. This is a toy example:
from collections import defaultdict
# fake data
titles = ['dog', 'cat']
colors = ['brown', 'yellow']
weight = [20, 2]
entries = defaultdict(dict)
for idx, title in enumerate(titles):
# make the new inner dictionary with one key:value pair, color
entries[title]['color'] = colors[idx]
# add to inner dictionary with second key:value pair
entries[title]['weight'] = weight[idx]
print(entries['cat'])
However, I'm not sure why you are using a nested dictionary when the keys to your outer dictionary are just Entry_0
and Entry_1
.... Why don't you just make a list of dictionaries with the schema that the list index is the entry number? You could then create dictionaries and append them to the list easily.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.