2012-02-06 93 views
2

我爲我的一個Web服務創建郵件「bot」,它將定期收集從PHP腳本發送的電子郵件隊列,並通過它Google的SMTP服務器。 PHP腳本在此格式返回消息:從字符串[Python]創建多級字典

[email protected]:Full Name:shortname\[email protected]:Another Full Name:anothershortname\[email protected]:Foo:bar 

我需要「轉換」是弄成這個樣子:

{ 
    "[email protected]": [ 
     [ 
      "Full Name", 
      "shortname" 
     ], 
     [ 
      "Foo", 
      "bar" 
     ] 
    ], 
    "[email protected]": [ 
     [ 
      "Another Full Name", 
      "anothershortname" 
     ] 
    ] 
} 

通知我需要每封郵件只有一個按鍵,連如果有多個地址實例。我知道我可以用兩個連續的循環來完成它,一個用於構建字典的第一級,第二個用於填充它,但應該有一種方法可以一次完成。這是到目前爲止我的代碼:

raw = "[email protected]:Full Name:shortname\[email protected]:Another Full Name:anothershortname\[email protected]:Foo:bar" 

print raw 

newlines = raw.split("\n") 

print newlines 

merged = {} 
for message in newlines: 
    message = message.split(":") 
    merged[message[0]].append([message[1], message[2]]) 

print merged 

我在循環的最後一行得到一個KeyError異常,我走的意思主要有任何附加到其之前存在(追加到一個不存在的鍵會不創建該密鑰)。

我是Python新手,對列表和字典還不是很熟悉,所以您的幫助非常感謝!

+0

+1所付出的努力。 – 2012-02-06 05:13:56

+0

您提供的結構無效。 – 2012-02-06 05:13:58

+0

@ IgnacioVazquez-Abrams - 正如我所說的,我還沒有熟悉字典和名單,這更像是一個僞結構(我認爲這實際上是有效的JSON)。只是爲了讓我形象化。 – 2012-02-06 05:16:16

回答

1

你是對的錯誤。所以你必須檢查鑰匙是否存在。 'key' in dict返回True如果在dict中發現'key',否則False。實現這個,這裏是你的完整的代碼(刪除調試打印語句):

raw = "[email protected]:Full Name:shortname\[email protected]:Another Full Name:anothershortname\[email protected]:Foo:bar" 
newlines = raw.split("\n") 
merged = {} 
for message in newlines: 
    message = message.split(":") 
    if message[0] in merged: 
     merged[message[0]].append([message[1], message[2]]) 
    else: 
     merged[message[0]]=[[message[1], message[2]]]  
print merged 

通告上的倒數第二個行嵌套列表額外的支架。

1

可能作爲工作:

for message in newlines: 
    message = message.split(":") 
    temp = [] 
    temp.append(message[1]) 
    temp.append(message[2]) 
    merged[message[0]] = temp 

實際上可能:

for message in newlines: 
    message = message.split(":") 
    temp = [] 
    temp.append(message[1]) 
    temp.append(message[2]) 
    if message[0] not in merged: 
     merged[message[0]] = [] 
    merged[message[0]].append(temp) 
0

只是檢查關鍵的存在,如果它不存在,創建密鑰, 如果它存在,然後追加將數據發送到現有列表。

if(messsage[0] in merged): 
    merged[message[0]] = [message[1],[message[2]] 
else: 
    merged[message[0]].append([[message[1], message[2]]) 
+0

括號不匹配。在第二行代碼中,應該是'[[message [1],message [2]]]'。 – 2012-02-06 05:30:24

+0

thanks.corrected。 – DhruvPathak 2012-02-06 05:34:05

1

我看你已經接受了答案,但也許你是無論如何感興趣,你在做什麼,可以用defaultdict可以輕鬆實現:

from collections import defaultdict 
raw = "[email protected]:Full Name:shortname\[email protected]:Another Full Name:anothershortname\[email protected]:Foo:bar" 

merged = defaultdict(list) 
for line in raw.split('\n'): 
    line = line.split(':') 
    merged[line[0]].append(line[1:])