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:

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

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 = {'':'24','':'32'}  #I will add here all subnet masks that I need.

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

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

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


Try something like this:

my_dict = {'':'24','':'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 *