How to get a random value from dictionary? How to get a random value from dictionary? python python

How to get a random value from dictionary?


One way would be:

import randomd = {'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()))


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.


Try this:

import randoma = dict(....) # a is some dictionaryrandom_key = random.sample(a, 1)[0]

This definitely works.