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:
JavaScript
x
5
1
10.10.1.20/255.255.255.0
2
40.50.1.10/255.255.255.224
3
18.1.14.50/255.255.255.128
4
18.1.28.50/255.255.255.248
5
My idea is to create a dictionary to replace the subnet masks into prefix masks, for example:
JavaScript
1
5
1
10.10.1.20/24
2
40.50.1.10/27
3
18.1.14.50/25
4
18.1.28.50/29
5
I am getting these IPs after using a small code to get IPs from a huge document, and my current code looks like this:
JavaScript
1
16
16
1
dict = {'255.255.255.0':'24','255.255.255.255':'32'} #I will add here all subnet masks that I need.
2
3
with open(r'C:UsersrobertSubnets.txt') as file:
4
contents = file.read().split('n')
5
subnet = []
6
for ele in contents:
7
if ele.__contains__('IP/Netmask'):
8
subnet.append(ele.split(':')[1])
9
10
11
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
12
13
subnet[:]=[dict.get(e,'') for e in subnet]
14
15
print(subnet) #This does not print anything, because I do not know how to replace just a portion of the string
16
Advertisement
Answer
Try something like this:
JavaScript
1
3
1
my_dict = {'255.255.255.0':'24','255.255.255.255':'32'}
2
subnet = [item.split('/')[0]+'/'+my_dict.get(item.split('/')[1], '') for item in subnet]
3
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.