Keval Shah
Keval Shah

Reputation: 17

Shuffle dictionaries of sets in Python

I am trying to shuffle dictionaries of sets. This is the set which I want to shuffle randomly

{'1': ['IMG_0001.png', 'IMG_0002.png', 'IMG_0003.png', 'IMG_0004.png'], 
 '2': ['IMG_0020.png', 'IMG_0021.png', 'IMG_0022.png', 'IMG_0023.png'], 
 '3': ['IMG_0051.png', 'IMG_0052.png', 'IMG_0053.png', 'IMG_0054.png']} 

Output should be somewhat like this below

{'1': ['IMG_0001.png', 'IMG_0002.png', 'IMG_0053.png', 'IMG_0054.png'], 
 '2': ['IMG_0020.png', 'IMG_0021.png', 'IMG_0022.png', 'IMG_0023.png'], 
 '3': ['IMG_0003.png', 'IMG_0004.png', 'IMG_0051.png', 'IMG_0052.png']}

Tried using random.shuffle() in python but not getting as expected. Can anyone help me. I am a new beginner in python. Thank you for your help.

Upvotes: 0

Views: 86

Answers (1)

Anakhand
Anakhand

Reputation: 2998

If each list should have the same size and you want to shuffle all the elements of the lists among each other, you could use the following function:

import random
import itertools


def shuffle(original: dict) -> dict:
    all_elements = list(itertools.chain.from_iterable(original.values()))
    m = len(all_elements) // len(original)  # list size
    random.shuffle(all_elements)
    return {k: all_elements[i*m : (i+1)*m] for i, k in enumerate(original)}

Or, with the more-itertools package:

import random
import itertools
import more_itertools


def shuffle(original: dict) -> dict:
    all_elements = list(itertools.chain.from_iterable(original.values()))
    list_length = len(all_elements) // len(original)
    random.shuffle(all_elements)
    return {k: l for k, l in more_itertools.sliced(all_elements, n=list_length)}

Sample usage:

d = {
    "1": ["IMG_0001.png", "IMG_0002.png", "IMG_0003.png", "IMG_0004.png"],
    "2": ["IMG_0020.png", "IMG_0021.png", "IMG_0022.png", "IMG_0023.png"],
    "3": ["IMG_0051.png", "IMG_0052.png", "IMG_0053.png", "IMG_0054.png"],
}
print(shuffle(d))
{'1': ['IMG_0023.png', 'IMG_0003.png', 'IMG_0021.png', 'IMG_0001.png'],
 '2': ['IMG_0053.png', 'IMG_0051.png', 'IMG_0052.png', 'IMG_0004.png'],
 '3': ['IMG_0054.png', 'IMG_0022.png', 'IMG_0002.png', 'IMG_0020.png']}

Upvotes: 1

Related Questions