How to get a random value in python dictionary

2019-01-03 13:14发布

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?

12条回答
手持菜刀,她持情操
2楼-- · 2019-01-03 13:21

Try this:

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

This definitely works.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-03 13:23

Since the original post wanted the pair:

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
country, capital = random.choice(list(d.items()))

(python 3 style)

查看更多
在下西门庆
4楼-- · 2019-01-03 13:24

If you don't want to use random.choice() you can try this way:

>>> list(myDictionary)[i]
'VENEZUELA'
>>> myDictionary = {'VENEZUELA':'CARACAS', 'IRAN' : 'TEHRAN'}
>>> import random
>>> i = random.randint(0, len(myDictionary) - 1)
>>> myDictionary[list(myDictionary)[i]]
'TEHRAN'
>>> list(myDictionary)[i]
'IRAN'
查看更多
冷血范
5楼-- · 2019-01-03 13:26

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.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-03 13:26
>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'

By calling random.choice on the keys of the dictionary (the countries).

查看更多
劳资没心,怎么记你
7楼-- · 2019-01-03 13:28

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

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(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()))
查看更多
登录 后发表回答