How to get a random value in python dictionary


Question

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?

1
130
5/15/2013 6:49:17 AM

Accepted Answer

One way (in Python 2.*) would be:

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

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()))
226
3/10/2019 7:12:54 PM

I wrote this trying to solve the same problem:

https://github.com/robtandy/randomdict

It has O(1) random access to keys, values, and items.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon