2

I have been thinking this through but I did not come to any conclusion (not that great with Python yet).

My dictionary looks like this:

{1: [dog, animal], 2: [square, shape], 3: [red, color]}

I am printing out the values but the dictionary is sorted by numbers, which is fine but I want to randomize it so I print out something like this:

3
red
color
1
dog
animal
2
square
shape

I know that list would be more ideal for this situation but this data is from existing structure that I cannot change. Maybe re-numbering the keys would do the trick?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user3056783
  • 2,265
  • 1
  • 29
  • 55

2 Answers2

6

Dictionaries are already listed in arbitrary order, they do not have a fixed order. See Why is the order in dictionaries and sets arbitrary? Any sense of order is a coincidence and depends on the insertion and deletion history of the dictionary.

That said, it's easy enough to further ensure a shuffled list with random.shuffle():

import random

items = yourdict.items()
random.shuffle(items)

for key, value in items:
    print key
    print '\n'.join(value)
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

You can randomize the keys:

import random
....
keys = dictionary.keys()
random.shuffle(keys)
for key in keys:
    print key, dictionary[key]
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • I would do `keys = list(dictionary)` to make it forward compatible. – mgilson May 26 '14 at 20:50
  • can you elaborate? python.org uses `keys()` in the note about `items()` and nothing is said in `keys()` itself... – Reut Sharabani May 26 '14 at 20:57
  • in python3.x, `keys` returns an object which is a lot more `set`-like. IIRC, it doesn't support the indexing which is required by `random.shuffle`. `list(d)` gives the same thing that `d.keys()` gave in python2.x. – mgilson May 26 '14 at 23:07