Search code examples
pythonnetwork-programminglist-comprehensiondictionary-comprehension

Can I made use of comprehensions for comparing these lists of dictionaries?


As title. I'm trying to figure out a comprehension for this. Getting stuck adding complexity to the basic code I built so far. I feel like this would actually be easier in a comprehension, but I couldn't find an example to build off of, so a jumpstart would be appreciated.

Scope:

  1. Try to match the list elements by dictionary's "network" value. Failing to find a match for old_routes' elements in new_routes should print a warning.
  2. If a match between the lists "network" value is found, compare those dictionaries' "nexthop_ip", and print whether the new_route's nexthop_ip has changed or stayed the same.
  3. I may need to run #2 comparison on other values as well.

Thanks in advance.

old_routes = [
    {
        "network": "10.11.11.11",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.155.155.155",
    },
    {
        "network": "10.22.22.22",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.99.99.99",
    },
    {
        "network": "10.33.33.33",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.66.66.66",
    }
]
new_routes = [
    {
        "network": "10.11.11.11",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.155.155.155",
    },
    {
        "network": "10.22.22.22",
        "distance": "20",
        "metric": "0",
        "nexthop_ip": "10.77.77.77",
    }
]

for old_route in old_routes:
    for new_route in new_routes:
        if old_route["network"] == new_route["network"]:
            if old_route["nexthop_ip"] == new_route["nexthop_ip"]:
                print(f"{new_route['network']} has no routing changes.")
            else:
                print(f"{new_route['network']} has changed nexthop IPs from {old_route['nexthop_ip']} to {new_route['nexthop_ip']}")

Solution

  • old_networks = set(route["network"] for route in old_routes)
    new_networks = set(route["network"] for route in new_routes)
    
    for network in old_networks - new_networks:
        print(f"Warning: {network} not found in new_routes")
    
    for new_route in new_routes:
        try:
            old_route = next(route for route in old_routes if route["network"] == new_route["network"])
            if old_route["nexthop_ip"] == new_route["nexthop_ip"]:
                print(f"{new_route['network']} has no routing changes.")
            else:
                print(f"{new_route['network']} has changed nexthop IPs from {old_route['nexthop_ip']} to {new_route['nexthop_ip']}")
        except StopIteration:
            print(f"Warning: {new_route['network']} not found in old_routes")
    

    The first portion takes care of routes that are missing from new_routes and the second takes care of requirement #2 (compares IPs and then nexthop).