Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading