How to get a random value from dictionary in python

tekknolagi picture tekknolagi · Feb 1, 2011 · Viewed 245.7k times · Source

How can I get a random pair from a dict? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.

The dict looks like {'VENEZUELA':'CARACAS'}

How can I do this?

Answer

Gerrat picture Gerrat · Feb 1, 2011

One way would be:

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

EDIT: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:

country, capital = random.choice(list(d.items()))