2016-11-10 79 views
0

想象一個充滿標準消息的文件。每條消息都有一個入站消息和多個出站消息。每條消息都有一個在入站和出站之間共享的唯一ID。我想要做的就是下一個ID關於構建Python字典

# Dictionary I am trying to build up 
data = {} 

for message in my_log_file: 
    details = {} 
    tag_11 = 'undef' 

    for tag in message.split('\001'): 
     if (I find something useful): 
      kv = tag.split('=') 
      key = kv[0] 
      val = kv[1] 

      # Found my id 
      if key == '11': 
       tag_11 = val   

      # Found data to be associated with this id 
      if key == '35' or key == '150': 
       details[key] = val 


    # Now trying to create an association 
    if 'undef' is not tag_11: 
     if data[str(tag_11)]: 
      data[tag_11].append(details) 
     else: 
      data[tag_11] = details 

我有什麼期望所有郵件的組細節

If tag_11 is 12804581 
If details is {'150': '4', '<': '06:19:45.262932', '35': '8'} 

I expect to see an association between the two 

我能得到什麼

Traceback (most recent call last): 
    File "ack.py", line 69, in ? 
    if data[str(tag_11)]: 
KeyError: '12804581' 

請幫我創建協會。在Java中來思考,我需要一個<String, List<o>>

+0

「我希望看到兩者之間的關聯:」這是令人難以置信的模糊。我們在這裏處理代碼,你可以非常精確。顯示你想要的字典實際上。 –

回答

0

認爲你想要的東西,如:

.... 
tag_11_key = str(tag_11) 
if 'undef' is not tag_11: 
    if tag_11_key not in data: 
     data[tag_11_key] = [] 

    data[tag_11_key].append(details) 
+0

進一步考慮這一點,將'data'設爲'defaultdict(list)'。但從教學的角度來看,你的答案是開始的地方。 –