I'm trying to take a list of hosts with network information and produce a list of unique subnets with a list of domains associated with the subnet. Example list of hosts, shortened to three but this could be several hundred/thousand of items:
hosts = [{
'name': 'foo',
'subnet_address': '192.168.1.0',
'subnet_mask': '255.255.254.0',
'domain': 'foo.example.com'
}, {
'name': 'bar',
'subnet_address': '192.168.2.0',
'subnet_mask': '255.255.254.0',
'domain': 'bar.example.com'
}, {
'name': 'baz',
'subnet_address': '192.168.2.0',
'subnet_mask': '255.255.254.0',
'domain': 'foo.example.com'
}]
Here's the kind of output I'm trying to achieve, the subnet_address is the unique key and I want to build a list of domain associations for them:
[{
'subnet_address': '192.168.1.0',
'subnet_mask': '255.255.254.0',
'domains': [
'foo.example.com'
]
}, {
'subnet_address': '192.168.2.0',
'subnet_mask': '255.255.254.0',
'domains': [
'bar.example.com',
'foo.example.com'
]
}]
I've found questions about removing duplicate dictionaries from a list and questions about merging (updating) dictionaries but haven't found anything similar to this yet, merging duplicates but at the same time building a list (set) of domains found elsewhere in the host list.
subnet_addressorsubnet_mask. You have to decide on one.subnet_addressis the "primary key", although I'm interested to know ifsubnet_addressandsubnet_maskcould be used together as the primary key..I suppose one could concatenate them together perhaps using the "192.168.1.0/23" format