How To Iterate Over A Python Dictionary In Random Order?

Summary: To iterate over the dictionary items in random order get the list of items in a tuple with .items() or get the list of keys with .keys() or extract the values in a list using .values() , then shuffle and iterate through this list using the shuffle() method of the random module.

Problem: Given a dictionary; how to iterate over all items in random order?

Example:

d = {
    'Roll 1': 'Tyson',
    'Roll 2': 'John',
    'Roll 3': 'Rock',
    'Roll 4': 'Brock',
    'Roll 5': 'Christopher'
}
# <Some Method/Procedure to iterate and display over the dictionary items in random order>

Output:

Roll 2 : John
Roll 1 : Tyson
Roll 5 : Christopher
Roll 3 : Rock
Roll 4 : Brock

In the above example, we see that the items within the dictionary have been displayed in random order. This is the aim of our discussion in this article.

Introduction

A dictionary in Python is generally an unordered set of key-value pairs. This means that the items in a dictionary do not have a defined order, i.e., you cannot refer to an item by using an index. Also, a dictionary Python doesn’t track the order of insertion, and iterating over it will produce the values in the order based on how the keys are stored in its hash table, which is in turn influenced by a random value to reduce collisions.

🔔 Info: A Python dictionary uses a data structure known as a hashmap. The key in a dictionary gets converted with the help of a hash algorithm from a string (or whatever) into an integer value, and it involves a couple of very simple calculations to use that integer value and search the right place in the dictionary to look.

When you iterate over a dictionary, it is effectively random. But as mentioned earlier it will produce values in order based on how the keys are stored in the hash table. Therefore, if you wish to explicitly randomize the sequence of key-value pairs in the dictionary, you need to work with a different object that is ordered. Hence, without further delay let us have a look at the different ways that allow us to randomize the key-value pairs in a dictionary.

❖ Convert Dictionary To List And Use The random.shuffle() Method

To randomize and iterate over the key-value pairs in the dictionary, you will have to convert it to a list and then use the shuffle() method to iterate over the items in random order.

💡 Note: shuffle is a built-in method of the random module in Python that accepts a sequence (like a list) and then rearranges the order of items in the sequence.

Here, you have three options:

  • shuffle the items.
  • shuffle the keys.
  • shuffle the values.

Let us dive into each method one by one.

Method 1: Shuffle Using dict.items()

The first approach uses the dictionary method dict.items() to retrieve an iterable of (key, value) tuples and then convert it to a list using the built-in list() constructor. Then use the shuffle() method of the random module upon the list of tuples containing (key, value) pairs to iterate over the items in random order.

Let us have a look at the following program to understand the concept behind the given explanation.

import random

d = {
    'Roll 1': 'Tyson',
    'Roll 2': 'John',
    'Roll 3': 'Rock',
    'Roll 4': 'Brock',
    'Roll 5': 'Christopher'
}

items = list(d.items())  # List of tuples of (key,values)
random.shuffle(items)
for key, value in items:
    print(key, ":", value)

Output:

Roll 2 : John
Roll 1 : Tyson
Roll 4 : Brock
Roll 3 : Rock
Roll 5 : Christopher

Using the items() method on the dictionary object is the most Pythonic way if everything you want is to retrieve a list of (key, value) pairs. However what if you want to randomize the items using the keys? That brings us to the next method.

Method 2: Shuffle Using dict.key()

To get a list of key values, use the dict.keys() method and pass the resulting iterable into a list() constructor. Then use the shuffle() method of the random module upon the list of the keys of the dictionary, to iterate over the items in random order.

import random

d = {
    'Roll 1': 'Tyson',
    'Roll 2': 'John',
    'Roll 3': 'Rock',
    'Roll 4': 'Brock',
    'Roll 5': 'Christopher'
}

keys = list(d.keys())  # List of keys
random.shuffle(keys)
for key in keys:
    print(key, ":", d[key])

Output:

Roll 1 : Tyson
Roll 4 : Brock
Roll 3 : Rock
Roll 2 : John
Roll 5 : Christopher

Method 3: Shuffle Using dict.value()

Instead of keys, you may want to iterate over the values in random order and ignore the keys. To get a list of values, use the dict.values() method and pass the resulting iterable into a list() constructor. Then use the shuffle() method of the random module upon the list of the values of the dictionary, to iterate over the items in random order.

import random

d = {
    'Roll 1': 'Tyson',
    'Roll 2': 'John',
    'Roll 3': 'Rock',
    'Roll 4': 'Brock',
    'Roll 5': 'Christopher'
}

values = list(d.values())
random.shuffle(values)
for value in values:
    print(value)

Output:

Christopher
John
Rock
Brock
Tyson

Method 4: Using a List Comprehension

List comprehension is a compact way of creating lists. The simple formula is [expression + context].

  • Expression: What to do with each list element?
  • Context: What elements to select? The context consists of an arbitrary number of for and if statements.

You can use list comprehension to modify each (key, value) pair from the original dictionary before you store the result in the new list and then use the shuffle() method of the random module upon the list to iterate over the items in random order.

import random

d = {
    'Roll 1': 'Tyson',
    'Roll 2': 'John',
    'Roll 3': 'Rock',
    'Roll 4': 'Brock',
    'Roll 5': 'Christopher'
}

r = ([(k, v) for k, v in d.items()])
random.shuffle(r)
for key, value in r:
    print(key, ":", value)

Output:

Roll 3 : Rock
Roll 1 : Tyson
Roll 2 : John
Roll 5 : Christopher
Roll 4 : Brock

❖ Convert Dictionary To a List And Use The random.sample() Method

sample() is a built-in method of the random module in Python that returns a list with a random selection of a specified number of items in a given sequence. You can use this method to iterate through the items in the dictionary by converting the items to a list using the items() method and then passing it as the first parameter to the random.sample() method and len(d) as the second parameter that specifies the number of items in the dictionary.

import random

d = {
    'Roll 1': 'Tyson',
    'Roll 2': 'John',
    'Roll 3': 'Rock',
    'Roll 4': 'Brock',
    'Roll 5': 'Christopher'
}

for item, value in random.sample(list(d.items()), len(d)):
    print(item, ":", value)

Output:

Roll 5 : Christopher
Roll 3 : Rock
Roll 4 : Brock
Roll 2 : John
Roll 1 : Tyson

Conclusion

With that, we come to the end of this article and I hope it helps you to iterate through the items in a dictionary in random order with ease. Please stay tuned and subscribe for more interesting solutions and articles!

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!