I am trying to understand the itertools library and my data looks like this.
devices = ['devicea', 'deviceb', 'devicec']
data = {'devicea': [{'ip': '192.168.1.1', 'vrf': 'aaa'}, {'ip': '192.168.1.2', 'vrf': 'aaa'}],
'deviceb': [{'ip': '10.1.1.1', 'vrf': 'bbb'}, {'ip': '10.1.1.2', 'vrf': 'bbb'}],
'devicec': [{'ip': '20.1.1.1', 'vrf': 'ccc'}, {'ip': '20.1.1.2', 'vrf': 'ccc'}]}
I would like to get the products of the ip of the combinations of the devices, e.g the result should look like this.
[(192.168.1.1, 10.1.1.1), (192.168.1.1, 10.1.1.2), (192.168.1.1, 20.1.1.1), 192.168.1.1, 20.1.1.2), (192.168.1.2, 10.1.1.1), (192.168.1.2, 10.1.1.2), (192.168.1.2, 20.1.1.1), (192.168.1.2, 20.1.1.2), (10.1.1.1, 20.1.1.1), (10.1.1.1, 20.1.1.2), (10.1.1.2, 20.1.1.1), (10.1.1.2, 20.1.1.2)]
using itertools.combinations I can get the pair of the possible combination of the devices.
device_combination = itertools.combinations(devices, 2)
How can I use itertools.products to find the products of the ip addresses?
>Solution :
Use itertools.combinations() to get all the pairs of devices. Then for each pair, use itertools.product() to get the cross product of IPs, and add these to the result.
result = []
for d1, d2 in itertools.combinations(data.values(), 2):
result.extend(itertools.product([i['ip'] for i in d1], [i['ip'] for i in d2])