MarcoPolo
MarcoPolo

Reputation: 83

Generating all the possible dicts from an existing dict in terms of values

I have a dictionary of

kwarg = {'a': 0 , 'b': 1 , 'c': 2} and I want to produce all the possible alternative dictionaries in terms of values such as:

x1={'a': 1 , 'b': 0 , 'c':2}

x2={'a': 1 , 'b': 2 , 'c':0}

x3={'a': 0 , 'b': 2 , 'c':1}

x4={'a': 0 , 'b': 1 , 'c':2}

x5={'a': 2 , 'b': 1 , 'c':0}

x6={'a': 2 , 'b': 0 , 'c':1}

but I have 6 elements (0,1,2,3,4,5) and need to use python algorytm.

Upvotes: 2

Views: 48

Answers (3)

Kshitij Dhyani
Kshitij Dhyani

Reputation: 843

This would be my take on it , more readable and basic :

import itertools
kwarg = {'a': 0 , 'b': 1 , 'c': 2}
val=list(kwarg.values())
new=list(itertools.permutations(val))
d=dict()
for i in range(0,len(new)):
    for j in range(0,len(new[i])):
        if j==0:
            d['a']=new[i][j]
        if j==1:
            d['b']=new[i][j]
        if j==2:
            d['c']=new[i][j]
    print(d)

Upvotes: 0

quant
quant

Reputation: 2214

Does python algorithm mean that you cannot use any predefined function / modue? If yes, the following code may be fine or provide a good starting point:

possibilites = [0, 1, 2, 3, 4, 5]

lstOfDicts = []
for a in possibilites:
    for b in possibilites:
        for c in possibilites:
            lstOfDicts.append({"a" : a, "b" : b, "c" : c})

print(lstOfDicts)

Upvotes: 0

Krishna
Krishna

Reputation: 1362

Following code in python3 should do

import itertools


def main():
    '''The Main'''

    kwarg = {'a': 0 , 'b': 1 , 'c': 2}
    keys = kwarg.keys()
    for comb in itertools.permutations(kwarg.values()):
        print(dict(zip(keys, comb)))



if __name__ == '__main__':
    main()

Upvotes: 5

Related Questions