Search code examples
pythondictionaryvariablesrandomkeyerror

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


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 -


Solution

  • 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()))