簡體   English   中英

嵌套字典 python 語法

[英]Nested dictionary python syntax

嘗試生成嵌套字典時遇到一些語法問題。 我的代碼嘗試如下:

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

給出了我正在尋找的東西(但是當試圖在入口鍵中添加額外的鍵:值對時,我得到語法錯誤:

 target_dict['Entry'+'_'+str(count)]['Sequence'+'_'+str(count)] = alignment.title,/
                                                                                     ^
SyntaxError: invalid syntax

所需的 output 是:

{'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',

我怎樣才能制作這個嵌套字典? 任何有關我如何在語法上出錯的幫助將不勝感激,謝謝!

我認為您正在嘗試錯誤地“添加到 [inner] 字典”。 這是一個玩具示例:

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'])

但是,當外部字典的鍵只是Entry_0Entry_1時,我不確定為什么要使用嵌套字典 .... 為什么不使用列表索引的架構制作字典列表入境號碼? 然后,您可以輕松地創建字典和 append 到列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM