pythonrandomdictionarykey

How can I get a random key-value pair from a dictionary?


In Python, given a dictionary like

{
    'VENEZUELA': 'CARACAS',
    'CANADA': 'OTTAWA'
}

How can I choose a random item (key-value pair)?

What if I only need the key, or only the value - can it be optimized?


Solution

  • Make a list of the dictionary's items, and choose randomly from that in the usual way:

    import random
    d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
    country, capital = random.choice(list(d.items()))
    

    Similarly, if only a value is needed, choose directly from the values:

    capital = random.choice(list(d.values()))