Pynewbie
Pynewbie

Reputation: 25

Map value from 1st key value pair to all values in 2nd key value pair in a python dictionary

I have a requirement to fetch dictionary items which contain lists. Suppose there are 2 key values pairs in my dictionary, I need to query each value from a 1st key value pair and map all the values from the 2nd key value pair & store it in a file. I am new to Python and have seen few online forums but nothing matched my requirement. Any help is greatly appreciated.

E.g.

My dictionary looks like this:

test_dict = {'Host': ['H1','H2'], 'IP':['IP1','IP2','IP3','IP4','IP5']}

My file should look like this which I will take it as input to my other program:

H1 IP1

H1 IP2

H1 IP3

H1 IP4

H1 IP5

H2 IP1

H2 IP2

H2 IP3

H2 IP4

H2 IP5

Please suggest.

Upvotes: 1

Views: 71

Answers (2)

Mohamad Al Mdfaa
Mohamad Al Mdfaa

Reputation: 1075

You can use product from itertools to do that:

>>> from itertools import product
>>> test_dict = {'Host': ['H1','H2'], 'IP':['IP1','IP2','IP3','IP4','IP5']}
>>> with open('file.txt', 'a') as f: # To Write The Output into a text file
...     print(*map(' '.join, product(test_dict['Host'], test_dict['IP'])), sep='\n', file=f)
...  
>>> with open('file.txt') as f: # To Read The File and Check The Result
...    print(f.read())
...
H1 IP1
H1 IP2
H1 IP3
H1 IP4
H1 IP5
H2 IP1
H2 IP2
H2 IP3
H2 IP4
H2 IP5

Upvotes: 3

Osman Mamun
Osman Mamun

Reputation: 2882

Use product form itertools to get all the pairs. And then write it into a file:

In [24]: from itertools import product

In [25]: test_dict = {'Host': ['H1','H2'], 'IP':['IP1','IP2','IP3','IP4','IP5']}

In [26]: with open('test.txt', 'w') as f:
    ...:     for i in product(test_dict['Host'], test_dict['IP']):
    ...:         f.write('{} {}\n'.format(*i))

In [27]: cat test.txt
H1 IP1
H1 IP2
H1 IP3
H1 IP4
H1 IP5
H2 IP1
H2 IP2
H2 IP3
H2 IP4
H2 IP5

Upvotes: 5

Related Questions