How to also get the index of a random choice json file list

Question:

I am writing a script for a book randomiser selection and I am wondering how do I also print the index number of the randomised choice that has been taken from a json list.

Below is my function for viewing all the data:

def view_data():
with open (filename, "r") as f:
    temp = json.load(f)
    i=0
    for entry in temp:
        name = entry["book"]
        print(f"Index Number {i}")
        print(f"Name of book: {name}")
        print("nn")
        i=i+1

When I run this it shows:

Index Number 0
Name of book: Fruit

Index Number 1
Name of book: Salad

Index Number 2
Name of book: Meat

Index Number 3
Name of book: Vegetables

Index Number 4
Name of book: Dinner

However when I call my randomiser function it doesn’t show the index also:

def random_select():
with open (filename, "r") as f:
    temp = json.load(f)
    data_length = len(temp)-1
    i=0
    book_randomiser = random.choice(temp)
    print(book_randomiser)

This function prints the below answer:

{'book': 'Salad'}

Is there a way to print the index of the book the randomiser selects?

Asked By: coding_journey

||

Answers:

You can use enumerate():

import random

temp = [
    {"book": "Fruit"},
    {"book": "Salad"},
    {"book": "Meat"},
    {"book": "Vegetables"},
    {"book": "Dinner"},
]

index, book = random.choice(list(enumerate(temp)))
print(index)
print(book)

Prints (for example):

3
{'book': 'Vegetables'}
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.