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

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()))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)