Replace just a string’s portion in a list from a dictionary

I am struggling when trying to replace string’s portions from a list, using a dictionary. I have a list with network IPs and subnet masks:

10.10.1.20/255.255.255.0
40.50.1.10/255.255.255.224
18.1.14.50/255.255.255.128
18.1.28.50/255.255.255.248

My idea is to create a dictionary to replace the subnet masks into prefix masks, for example:

10.10.1.20/24
40.50.1.10/27
18.1.14.50/25
18.1.28.50/29

I am getting these IPs after using a small code to get IPs from a huge document, and my current code looks like this:

dict = {'255.255.255.0':'24','255.255.255.255':'32'}  #I will add here all subnet masks that I need.

with open(r'C:UsersrobertSubnets.txt') as file:
  contents = file.read().split('n')
  subnet = []
  for ele in contents:
    if ele.__contains__('IP/Netmask'):
        subnet.append(ele.split(':')[1])


print(subnet)     #This works fine and I can get all the IPs/Mask from the document in this format: 10.10.1.20/255.255.255.0

subnet[:]=[dict.get(e,'') for e in subnet]

print(subnet)     #This does not print anything, because I do not know how to replace just a portion of the string

Answer

Try something like this:

my_dict = {'255.255.255.0':'24','255.255.255.255':'32'}
subnet = [item.split('/')[0]+'/'+my_dict.get(item.split('/')[1], '') for item in subnet]

This will also replace your subnet masks with empty strings if a corresponding prefix mask is not present in the dictionary.

Also dict is a keyword in python dont use it as variable names.

Leave a Reply

Your email address will not be published. Required fields are marked *