N
N
nedland2022-04-20 11:54:46
Python
nedland, 2022-04-20 11:54:46

Derive random key from json dictionary?

The essence of the question is how to derive a random key from a json dictionary.
Googled everything that is possible, some crutches and a code of 10 lines, and that does not work. Isn't there an easy way.

def randkey():
    with open("file.json") as file:
        dict = json.load(file)
       
    for k, v in sorted(dict.items())[-1:]:
        randkeyvalue =   f"Имя: {v['Name']}\n" \
                         f"Возраст: {v['Age']}\n"


At the moment, it displays one last entry, but I would like a random one.
Prompt people kind, thanks
COMPLETE:
See if I can sort the dictionary in reverse order ( sorted() ) and take the very first value from it [-1:]. Can I sort it RANDOMLY (randomly) and take the first value and of course it will always be different.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2022-04-20
@nedland

Derive random key from json dictionary

So key or value? So from a dictionary or from JSON?
Derive random key from json dictionary

from random import choice
choice(list(dct.keys()))

N
nedland, 2022-04-20
@nedland

import random

def randitem():
    with open("file.json") as file:
        dict = json.load(file)

    dictlist = list(dict.items())
    random.shuffle(dictlist)  
       
    for k, v in dictlist[-1:]:
        randkeyvalue =   f"Имя: {v['Name']}\n" \
                         f"Возраст: {v['Age']}\n"

I did it like this, it works as it should. If [-1:] is changed to -2, -3, etc. output as many random items. SPS everyone.
PS
dictlist = random.shuffle(list(dict.items()))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question