4

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Dhruv Ghulati
  • 2,976
  • 3
  • 35
  • 51
  • `random.shuffle` should work. Not sure why it's giving you a None-type object. – RobertR Jun 15 '16 at 19:33
  • If you want to randomly shuffle the elements of a list, independently of what they are, just use [`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle). Otherwise define what you mean by randomly shuffle. Note that `random.shuffle` **modified** the original list. Use it as: `my_list = [...]; random.shuffle(my_list); print(my_list)` – Bakuriu Jun 15 '16 at 19:34
  • 6
    `random.shuffle` shuffles the list in place and returns `None`. You are probably doing `x = random.shuffle(x)` when you should be doing `random.shuffle(x)` without assignment. – Steven Rumbalski Jun 15 '16 at 19:35
  • See @StevenRumbalski's response! – Brian Jun 15 '16 at 19:36
  • You are absolutely right all of you :) Please don't downvote, nothing in the python docs specifies that it returns a NoneType object, genuine silly error I think others would benefit from knowing about. – Dhruv Ghulati Jun 15 '16 at 19:42
  • @DhruvGhulati: Interesting. The docs online say "Shuffle the sequence x in place." They say nothing about the return type, but it is a convention in Python that mutating methods and functions return `None`. Oddly enough if you type `help(random.shuffle)` in the interpreter you get "shuffle list x in place; return None." – Steven Rumbalski Jun 15 '16 at 19:54

1 Answers1

13

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)
RobertR
  • 745
  • 9
  • 27