mardi 12 avril 2022

How do I take a specific dictionary item along with it's key randomly? [duplicate]

Take a look at this example:

dictionary = {"hello":"world", "yes":"sir", "very":"funny", "good":"bye"}

Now if I want to pick a random item (along with it's key) from this dictionay, how would I do that? I tried:

random.choice(dictionary)

But it does not work and returns this traceback error:

  File "C:\Users\dado\AppData\Local\Programs\Python\Python310-32\lib\random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
KeyError: 3

I want to take a random item with it's key and store each of those in variables like this:

random_item = # Code to grab a random item
random_items_key = # Code to grab that random item's key

So if we ranodmly selected:

("hello":"world")

The value of the variables would be:

random_item = # This would be "hello"
random_items_key = # And this should be "world"

So how do we grab a random pair from a dictionary in python? And how do we store each in different variables? Would appreciate some help, thanks -




Aucun commentaire:

Enregistrer un commentaire