Aliko Aliko
Aliko Aliko

Reputation: 65

python convert dictionary components to permutations

I got the following dictionary

[ {1a,1b},{2a,2b},{3a,3b},{4a,4b}]

I want to loop through the values to get 16 distinct dictionaries example

[1a,2a,3a,4a]
[1a,2a,3a,4b]

.............
[1b,2b,3b,4b]

How can i go about it in python

Upvotes: 0

Views: 47

Answers (2)

EL-AJI Oussama
EL-AJI Oussama

Reputation: 426

use itertools.product()

import itertools
array = [{"1a", "1b"}, {"2a", "2b"}, {"3a", "3b"}, {"4a", "4b"}]
conbination = list(itertools.product(*array))
conbination = list(map(list, conbination))
print(conbination)

Output

[['1a', '2b', '3a', '4a'], ['1a', '2b', '3a', '4b'], ['1a', '2b', '3b', '4a'], ['1a', '2b', '3b', '4b'], ['1a', '2a', '3a', '4a'], ['1a', '2a', '3a', '4b'], ['1a', '2a', '3b', '4a'], ['1a', '2a', '3b', '4b'], ['1b', '2b', '3a', '4a'], ['1b', '2b', '3a', '4b'], ['1b', '2b', '3b', '4a'], ['1b', '2b', '3b', '4b'], ['1b', '2a', '3a', '4a'], ['1b', '2a', '3a', '4b'], ['1b', '2a', '3b', '4a'], ['1b', '2a', '3b', '4b']]

Upvotes: 1

Yuchen Ren
Yuchen Ren

Reputation: 307

You can convert the dictionary to 2 lists and use double loop like this.

dic = {"1a": "1b", "2a": "2b", "3a": "3b", "4a": "4b"}
list1 = []
list2 = []
for a, b in dic.items():
    list1.append(a)
    list2.append(b)
for i in range(len(dic)):
    for j in range(len(dic)):
        print(list1[i], list1[j], list2[i], list2[j])

Upvotes: 0

Related Questions