Home > Back-end >  How to also get the index of a random choice json file list
How to also get the index of a random choice json file list

Time:09-07

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("\n\n")
        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?

CodePudding user response:

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'}
  • Related