[python]Making a list of dictionaries

Use case
I am trying to write a script for doing security group based on user’s input. the IpRanges is a list of dictionary. I intend to do a method which generate multiple dictionaries with the same key but different values, and put these dictionaries into a list.

ipaddress.ip_network method can evaluate both host ip address and ip subnet, if the value is not a valid subnet or ipv4 address an exception will be thrown, the collection will be based on only valid subnet or host ip address.

from ipaddress import ip_network
results = []
process_results = []
stop = int(input("how many source ip address you want"))
print("Press enter with empty response to quit.")
for i in range(0,stop):
    ip = input("Source address:")
    if ip is not "":
        try:
            ip_network(ip)
            results.append(ip)
        except ValueError as e:
            print(e)
    else:
        break
# collecting the dictionary / dictionaries in a list
for result in results:
    results_dict = {'ip': result}
    process_results.append(results_dict)
print(process_results)

Test case 1: mixture of ip address and subnets
Screenshot 2019-05-08 at 3.57.30 PM

Test case 2: mixture of ip address, subnet and empty input
Screenshot 2019-05-08 at 5.58.47 PM

Test case 3: mixture of ip address, invalid data and subnet
Screenshot 2019-05-08 at 6.00.27 PM
Screenshot 2019-05-08 at 6.01.09 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s