0

I have the following dictionary:

d = {
     'A': 50, 
     'B': 30, 
     'C': 20
      }

Is it possible to find and print all iterations of this dictionary based only on swapping the values?

E.g.

# First iteration
d = {'A': 50, 'B': 30, 'C': 20}

# Second iteration
d = {'A': 50, 'B': 20, 'C': 30}

# Third iteration
d = {'A': 30, 'B': 50, 'C': 20}

...

The values are unique and the order of swapping the values does not matter as long as all possible iterations are found.

Joseph
  • 586
  • 1
  • 13
  • 32

5 Answers5

3

We can obtain possible permutations using itertools library from stdlib

>>> from itertools import permutations
>>> d = {
     'A': 50, 
     'B': 30, 
     'C': 20
      }
>>> [dict(zip(d.keys(), values)) for values in permutations(d.values())]
[{'A': 50, 'B': 30, 'C': 20},
 {'A': 20, 'B': 30, 'C': 50},
 {'A': 30, 'B': 50, 'C': 20},
 {'A': 20, 'B': 50, 'C': 30},
 {'A': 30, 'B': 20, 'C': 50},
 {'A': 50, 'B': 20, 'C': 30}]
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
1

Use itertools.permutations:

from itertools import permutations

d = {
     'A': 50, 
     'B': 30, 
     'C': 20
      }

vals = d.values()    
for x in permutations(vals, len(vals)):
    x = iter(x)
    print({k: next(x) for k in d})

# {'A': 50, 'B': 30, 'C': 20}
# {'A': 50, 'B': 20, 'C': 30}                                  
# {'A': 30, 'B': 50, 'C': 20}                                 
# {'A': 30, 'B': 20, 'C': 50}                                
# {'A': 20, 'B': 50, 'C': 30}                               
# {'A': 20, 'B': 30, 'C': 50}
Austin
  • 25,759
  • 4
  • 25
  • 48
1

You can using permutation in itertools:

import itertools
[dict(zip(d.keys(), l)) for l in itertools.permutations(d.values())]
OmG
  • 18,337
  • 10
  • 57
  • 90
1

I don't know of any direct way to do this but you can make a permutation of the keys themselves (i.e "abc", "acb", "bac", "bca" etc') and use that to get the permutated values to your set.

for example with the permutated key set 'bca': key "a" gets the content of original dictionary "b". key "b" gets the content of original dictionary "c". key "c" gets the content of original dictionary "a".

and I'd get the permutated keyset from this question: Finding all possible permutations of a given string in python

BarSahar
  • 69
  • 1
  • 4
1

if you make a set with the keys and values you can use the itertools module, the combinations() function. From the result you eliminate the pairs with only keys.

here are details: https://docs.python.org/2/library/itertools.html#itertools.combinations

Petronella
  • 2,327
  • 1
  • 15
  • 24