1

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 -

Hyperba
  • 89
  • 3
  • 12
  • use random.choice on the keys. `randomKey = random.choice(myDict.keys())` then the value of that key is `randomValue = myDict[myKey]` –  Apr 12 '22 at 13:54
  • Check out [this answer](https://stackoverflow.com/a/4859322/2221001) on the marked duplicate, it's exactly what you are looking for. – JNevill Apr 12 '22 at 13:55
  • That does explain how to take a random pair, thanks. But how do I store each in a separete variable? – Hyperba Apr 12 '22 at 13:56
  • Sembei Norimaki Thanks! – Hyperba Apr 12 '22 at 13:58
  • To use `random.choice` you need to convert the dictionary into an iterable, I would recommend using `.items()` to get a list of tuples: https://replit.com/@LukeStorry/71843959#main.py – Luke Storry Apr 12 '22 at 13:58
  • @Hyperba If below answer helped you, can you please also upvote it by clicking the up arrow icon next to it? – Moinuddin Quadri Oct 26 '22 at 11:57

1 Answers1

0

You can get the desired behaviour using random.choice() on your dict.keys() (i.e. list containing the keys of the dict), which will return you a random key. And then you can use that key to get corresponding value. For example:

>>> import random
>>> my_dict = {"hello":"world", "yes":"sir", "very":"funny", "good":"bye"}

# Pick random key from your dict
>>> random_key = random.choice(list(my_dict.keys()))  # For example: "very"

# Get value corresponding to random key  
>>> my_dict[random_key]  # will return "funny"

OR, to get key and value together, you can do random.choice() on dict.items(). For example:

key, value = random.choice(list(my_dict.items()))
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126