如何从python中的字典中获取随机值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4859292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a random value from dictionary in python
提问by tekknolagi
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.
如何从 a 中获得随机对dict?我正在制作一个游戏,你需要猜测一个国家的首都,我需要随机出现问题。
The dictlooks like {'VENEZUELA':'CARACAS'}
的dict模样{'VENEZUELA':'CARACAS'}
How can I do this?
我怎样才能做到这一点?
采纳答案by Gerrat
One way (in Python 2.*) would be:
一种方法(在 Python 2.* 中)是:
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()))
回答by user225312
>>> 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.choiceon the keysof the dictionary (the countries).
通过在字典(国家/地区)上调用random.choicekeys。
回答by carl
Since this is homework:
由于这是家庭作业:
Check out random.sample()which will select and return a random element from an list. You can get a list of dictionary keys with dict.keys()and a list of dictionary values with dict.values().
检查random.sample()哪个将从列表中选择并返回随机元素。您可以使用 获取字典键dict.keys()列表和字典值列表dict.values()。
回答by patriciasz
If you don't want to use the randommodule, you can also try popitem():
如果您不想使用该random模块,也可以尝试popitem():
>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)
Since the dictdoesn't preserve order, by using popitemyou get items in an arbitrary (but not strictly random) order from it.
由于dict不保留 order,通过使用popitem您可以从中获得任意(但不是严格随机)顺序的项目。
Also keep in mind that popitemremoves the key-value pair from dictionary, as stated in the docs.
还要记住,popitem从字典中删除键值对,如文档中所述。
popitem() is useful to destructively iterate over a dictionary
popitem() 对于破坏性地迭代字典很有用
回答by Milad Mohammad Rezaei
If you don't want to use random.choice() you can try this way:
如果你不想使用 random.choice() 你可以试试这种方式:
>>> 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'
回答by Rob T
I wrote this trying to solve the same problem:
我写这个试图解决同样的问题:
https://github.com/robtandy/randomdict
https://github.com/robtandy/randomdict
It has O(1) random access to keys, values, and items.
它具有对键、值和项目的 O(1) 随机访问。
回答by lavee_singh
Try this:
尝试这个:
import random
a = dict(....) # a is some dictionary
random_key = random.sample(a, 1)[0]
This definitely works.
这绝对有效。
回答by Anivarth
I am assuming that you are making a quiz kind of application. For this kind of application I have written a function which is as follows:
我假设您正在制作一种测验类型的应用程序。对于这种应用程序,我编写了一个函数,如下所示:
def shuffle(q):
"""
The input of the function will
be the dictionary of the question
and answers. The output will
be a random question with answer
"""
selected_keys = []
i = 0
while i < len(q):
current_selection = random.choice(q.keys())
if current_selection not in selected_keys:
selected_keys.append(current_selection)
i = i+1
print(current_selection+'? '+str(q[current_selection]))
If I will give the input of questions = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}and call the function shuffle(questions)Then the output will be as follows:
如果我将给出输入questions = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}并调用该函数,shuffle(questions)那么输出将如下所示:
VENEZUELA? CARACAS CANADA? TORONTO
You can extend this further more by shuffling the options also
您还可以通过调整选项来进一步扩展
回答by Herman Yanush
Try this (using random.choice from items)
试试这个(使用 random.choice from items)
import random
a={ "str" : "sda" , "number" : 123, 55 : "num"}
random.choice(list(a.items()))
# ('str', 'sda')
random.choice(list(a.items()))[1] # getting a value
# 'num'
回答by OBu
Since the original post wanted the pair:
由于原始帖子想要这对:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
country, capital = random.choice(list(d.items()))
(python 3 style)
(蟒蛇3风格)

