2012-12-07 61 views
0

我需要從Oracle數據庫的數據讀入一個陣列中後,以一個perl散列到嵌套,鍵控Python字典平移。什麼是最有效的方法來做到這一點?現有的Perl代碼(我不知道的Perl在所有)看起來是這樣的:Perl來的Python:哈希嵌套字典和cx_Oracle

# read the data and place into a species hash (sphash) and a data hash (tmphash) 
my (@lnarr, %sphash, %tmphash, $tmpln, $tmpsel, $x, $datetime) ; 
while (@lnarr = $csr->fetchrow_array) { 
    $datetime = $lnarr[4].'-'.$lnarr[5] ; 
    $tmpln = join '_', $lnarr[8], $lnarr[9] ; 
    $sphash{$lnarr[7]} = 'x'; 
    $tmphash{$lnarr[0].'_'.$lnarr[1].'_'.$lnarr[2].'_'.$lnarr[3].'_'.$datetime.'_'.$lnarr[6]}{$lnarr[7]} .= $tmpln ; 
} #while line 

我不知道是什麼創造一個嵌套的字典將是最有效的途徑......任何指導,將是巨大的。我的初始代碼看起來像這樣,但我意識到它可能是非常錯誤的(我也只是在學習python): 前幾行是從Oracle輸出讀取元組到字典中的基礎,這個元組基於這個帖子:here

#this is creating the dictionary from the data 
cursor.execute(query, cruise6_input=cruise6_input) 
desc=[d[0] for d in cursor.description] 
result=[dict(zip(desc,line)) for line in cursor] 

station=[r['STATION'] for r in result] 
time=[r['GMT_TIME']for r in result] 
svspp=[r['SVSPP'] for r in result] 
expcatchwt=[r['EXPCATCHWT'] for r in result] 
beglat=[r['BEGLAT'] for r in result] 
expcatchnum=[r['EXPCATCHNUM'] for r in result] 
cruise=[r['CRUISE'] for r in result] 
towdate=[r['BEGIN_GMT_TOWDATE'] for r in result] 
stratum=[r['STRATUM'] for r in result] 
beglon=[r['BEGLON'] for r in result] 

tmpln=zip(expcatchwt,expcatchnum) 
tmphash=zip(station,time,beglat,cruise,towdate,stratum,beglon) 
keys=zip(tmphash,svspp) 

,我怎麼把tmphash [svspp] = tmpln的輸出?如果我打印tmphash [svspp]的結果是簡單地{} ....

回答

2

在Python字典項目訪問使用dictionary[key];所以你需要糾正線sphashtmphash

sphash[result[7]] = 'x' 
tmphash[result[0] + '_' + result[1] + '_' + result[2] + '_' + result[3] + '_' + datetime + '_' + 
     result[6]][result[7]] = tmpln 

這假定tmphash[somekey]本身已經是一個字典。您可以定義爲defaultdict

from collections import defaultdict 

tmphash = defaultdict(dict) 

現在每個tmphash鍵可以自動訪問時是另一個dict

+0

如何進行編輯的代碼看看嗎?使用set vs sphash有什麼好處? –

+0

@VictoriaPrice:由於您只使用dict來跟蹤唯一密鑰,一組更有效(無需存儲所有的'x'值)。 –

0

糾正你的Python代碼,以我abillity的:

# I have no idear what this is suppose to do 
# i guess you are trying to mimic the array assignment in 
# the while loop...but I think you are doing it wrong, please update your 
# poste so we can make sense of it 
desc=[d[0] for d in cursor.description] 
# makes a list of dicts with the entire desc array as key and one line as value?!?! 
result=[dict(zip(desc,line)) for line in cursor] 

tmphash = {} 
spset=set() # if you want an spset instead of hash 
while (True): # this should probably be a for loop with your array 
    datetime="%s-%s" % results[4:6] 
    tmpln='_'.join(result[8:10]) 
    # here you probberbly want to add to a set instead of making a hash mapping to something useless 
    sphash[result[7]]='x' 
    # or 
    spset.add(result[7]) 
    # .= is a string concatination operator in perl 
    # += can also concatinate strings in python 
    tmphash['_'.join(result[0:4]+[datetime]+result[6:8]] += tmpln