0

Imagine a file full of standard messages. Every message has 1 inbound and multiple outbound messages. Each message has a unique id shared across inbound and outbound. What I want to do is group details of all messages under one id

# 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

What I expect

 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

What I get

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

Please help me create an association. Thinking in Java terms, I need a <String, List<o>>

James Raitsev
  • 82,013
  • 132
  • 311
  • 454
  • " I expect to see an association between the two" this is incredibly vague. We're dealing with code here, you can be perfectly precise. Show what you want the dictionary to actually be. – Alex Hall Nov 10 '16 at 19:56

1 Answers1

0

I think you want something like:

....
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)
Jack
  • 18,975
  • 11
  • 46
  • 47
  • Taking this further, make `data` a `defaultdict(list)`. But from a teaching perspective, your answer is the place to start. – Alex Hall Nov 10 '16 at 19:59