Home > OS >  key error when trying to split two entries in a dictionary in python
key error when trying to split two entries in a dictionary in python

Time:07-06

i have a dictionary with entries that have the ip and ports displayed like this

{'source': '192.168.4.1:80', 'destination': '168.20.10.1:443'}

but i want it to display it like

{'src_ip': '192.168.4.1', 'src_port': 80, 'dest_ip': '168.20.10.1', 'dest_port': 443}

so i want to split the first two entries into 4 new ones and delete the two old ones. my code currently looks like this:

log entry = {'source': '192.168.4.1:80', 'destination': '168.20.10.1:443'}


def split_ip_port(log_entry):

   u_source = log_entry['source']
   if ':' in u_source:
       src_list = u_source.split(':')
       src_ip = src_list[0]
       src_port = src_list[1]
       log_entry.update({'src_ip': src_ip})
       log_entry.update({'src_port': src_port})
       del log_entry['source']
    
   u_dest = log_entry['destination']
   if ':' in u_dest:
       dest_list = u_dest.split(':')
       dest_ip = dest_list[0]
       dest_port = dest_list[1]
       print(dest_list)
       log_entry.update({'dest_ip': dest_ip})
       log_entry.update({'dest_port': dest_port})
       del log_entry['destination']
   return log_entry

when i try to test the source it gives me keyerror :'destination' and when i try to test the destination it gives me keyerror source. what is happening here?

CodePudding user response:

When you split value (e.g., log_entry['source'].split(":") ) it returns list ['192.168.4.1','80']. Then you have to return value by index from list, [0] index in list is '192.168.4.1'. Then you have to assign it to new key in your dict, log_entry['src_ip']

log_entry['src_ip']  = log_entry['source'].split(":")[0]
log_entry['src_port'] = log_entry['source'].split(":")[1]
log_entry['dest_ip'] = log_entry['destination'].split(":")[0]
log_entry['dest_port'] = log_entry['destination'].split(":")[1]
del log_entry['source']
del log_entry['destination']

CodePudding user response:

Since the original code work. Here just an offer to simplify the original code - you could try to split the source/destination and ports then just create a new dictionary like this way:

orig_dc = {'source': '192.168.4.1:80', 'destination': '168.20.10.1:443'}

new_dc = {}

for k, v in orig_dc.items():
    orig, port = v.split(':')

    if k in 'source':
        new_dc.setdefault('src_ip', orig)
        new_dc.setdefault('src_port', int(port))
    else:
        new_dc.setdefault('dest_ip', orig)
        new_dc.setdefault('dest_port', int(port))
    
    

expected = { 'src_ip': '192.168.4.1', 'src_port': 80,
             'dest_ip': '168.20.10.1', 'dest_port': 443}
             

assert new_dc == expected
  • Related