How to print a Python dictionary randomly?

PythonServer Side ProgrammingProgramming

Python dictionary is not iterable. Hence it doesn’t have index to be randomized. Instead collection of its keys is iterable and can be randomized by shuffle() function in random module. Using shuffled keys we can print associated values.

>>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> import random
>>> l=list(D1.keys())
>>> l
['pen', 'pencil', 'book', 'sharpner', 'eraser']
>>> random.shuffle(l)
>>> l
['pencil', 'eraser', 'sharpner', 'book', 'pen']
>>> for k in l:
    print (k,D1[k])

pencil 10
eraser 5
sharpner 5
book 100
pen 25
Published on 29-Dec-2017 18:32:44