1

The essence of the question is how to derive a random key/value from a JSON dictionary.

def randkey():
    with open("file.json") as file:
        dict = json.load(file)
       
    for k, v in sorted(dict.items())[-1:]:
        randkeyvalue =   f"Name: {v['Name']}\n" \
                         f"Age: {v['Age']}\n"

If I can sort the dictionary in reverse order (sorted()) and take the very first value from it [-1:]. Can I sort it randomly and take the first value and of course it will always be different?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
pixcen
  • 21
  • 4
  • 1
    "sort it randomly" is an oxymoron. – jonrsharpe Apr 20 '22 at 09:37
  • @jonrsharpe: err... I'm sure Kevlin Henney would take issue with that statement. – quamrana Apr 20 '22 at 09:39
  • @quamrana he can tell me himself, if he ever finishes sorting that list... And even though the sorting _process_ is random, the result isn't. – jonrsharpe Apr 20 '22 at 09:44
  • Thx all) agree, my logic is simple in words) it would be easy to just do randomly() instead of sorted() and the dictionary would be shuffled randomly) – pixcen Apr 20 '22 at 09:47
  • _"shuffled randomly"_ - then... `random.shuffle`? It seems like you didn't research this at all. – jonrsharpe Apr 20 '22 at 09:51
  • @jonrsharpe: lol. That's exactly what he did. And that's how I know about it. – quamrana Apr 20 '22 at 10:04
  • @jonrsharpe: 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"Name: {v['Name']}\n" \ f"Age: {v['Age']}\n" BIG THX BRO, now i can change [-1:] to -2 -3 else to derive more random items) – pixcen Apr 20 '22 at 10:37

1 Answers1

3

You can use the choice function from random:

For example:

>>> from random import choice
>>>
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>>
>>> choice(list(d))
'a'
>>> choice(list(d))
'c'
>>> choice(list(d))
'c'
>>> d
{'a': 1, 'b': 2, 'c': 3}
Brandt
  • 5,058
  • 3
  • 28
  • 46
  • 1
    Perhaps you could add some code to show exactly how `choice()` would be used to select a random key/value from a `dict`. – quamrana Apr 20 '22 at 09:38