Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

itertools combinations and products

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading