shuffle dictionary values in python

Viewed 1844

I have a dictionary and I want to shuffle the values, not the keys. For example:

{"a": "ACAT", "b": "ACTG", "c": "ACCC"}

and after shuffle:

{"a": "ACAT", "b": "ACTG", "c": "ACCC"}

but I don't know how I can do this work in python. I will be grateful if you help me.

4 Answers

You can use random.sample to get a random ordered list of the dict's values, then map them with the keys in their default order. At the difference of using shuffle you can do this in once

from random import sample

result = dict(zip(values, sample(list(values.values()), len(values))))

Run that 10 times

{'a': 'ACAT', 'b': 'ACCC', 'c': 'ACTG'}
{'a': 'ACTG', 'b': 'ACCC', 'c': 'ACAT'}
{'a': 'ACCC', 'b': 'ACTG', 'c': 'ACAT'}
{'a': 'ACTG', 'b': 'ACAT', 'c': 'ACCC'}
{'a': 'ACAT', 'b': 'ACCC', 'c': 'ACTG'}
{'a': 'ACCC', 'b': 'ACTG', 'c': 'ACAT'}
{'a': 'ACCC', 'b': 'ACTG', 'c': 'ACAT'}

The random module has a function that shuffles in-place.

So we can get the dict's values, shuffle them, and construct a new dict.

Demo:

>>> import random
>>> d = {
...     "a": "ACAT",
...     "b": "ACTG",
...     "c": "ACCC"
... }
>>> shuffled = list(d.values())
>>> random.shuffle(shuffled)
>>> dict(zip(d, shuffled))
{'a': 'ACCC', 'b': 'ACTG', 'c': 'ACAT'}

You can use a for loop and random.shuffle to shuffle the values of the dict, while changing the original dict.

Code:

import random

d = {"a": "ACAT", "b": "ACTG", "c": "ACCC"}

vals = list(d.values())
random.shuffle(vals)

for i, key in enumerate(d): d[key] = vals[i]

Explanation:

  • import random, importing the random module
  • d = {"a": "ACAT", "b": "ACTG", "c": "ACCC"}, setting d to a dict
  • vals = list(d.values()), setting val to a list of all values of d
  • random.shuffle(vals), shuffling vals
  • for i, key in enumerate(d): d[key] = vals[i], changing d to the random values

You can't really shuffle the values of the dictionary by simple writing:

shuffle(my_dict.values())

This will raise TypeError. But what you can do is to convert dictionary keys and values into a list, and then shuffle. Try the following code:

from random import shuffle

my_dict = {
    "a": "ACAT",
    "b": "ACTG",
    "c": "ACCC",
}

key_list = list(my_dict.keys())
values_list = list(my_dict.values())
shuffle(values_list)

for i in range(len(key_list)):
    my_dict[key_list[i]] = values_list[i]
Related