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?
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?
Try this:
This definitely works.
Since the original post wanted the pair:
(python 3 style)
If you don't want to use random.choice() you can try this way:
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.
By calling random.choice on the
keys
of the dictionary (the countries).One way (in Python 2.*) would be:
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: