Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly shuffling a list of dictionaries [duplicate]

A similar question I saw on Stack Overflow dealt with a dict of lists (was a bad title), and when I tried using random.shuffle on my list of dicts per that answer, it made the whole object a None-type object.

I have a list of dictionaries kind of like this:

[
{'a':'1211', 'b':'1111121','c':'23423'},
{'a':'101', 'b':'2319','c':'03431'},
{'a':'3472', 'b':'38297','c':'13048132'}
]

I want to randomly shuffle like this.

[
{'a':'3472', 'b':'38297','c':'13048132'},
{'a':'1211', 'b':'1111121','c':'23423'},
{'a':'101', 'b':'2319','c':'03431'}   
]

How can I do this?

like image 384
Dhruv Ghulati Avatar asked Oct 23 '25 05:10

Dhruv Ghulati


1 Answers

random.shuffle should work. The reason I think you thought it was giving you a None-type object is because you were doing something like

x = random.shuffle(...)

but random.shuffle doesn't return anything, it modifies the list in place:

x = [{'a':'3472', 'b':'38297','c':'13048132'},
     {'a':'1211', 'b':'1111121','c':'23423'},
     {'a':'101', 'b':'2319','c':'03431'}]
random.shuffle(x)  # No assignment
print(x)
like image 197
RobertR Avatar answered Oct 24 '25 21:10

RobertR