【问题标题】:Get a random subset of a dictionary获取字典的随机子集
【发布时间】:2018-11-02 19:46:54
【问题描述】:

免责声明:我知道有个问题叫

Get a random sample of a dict

但我的不是重复的,很明显。该问题的答案主要集中在计算字典的随机子集的值的总和,因为这正是 OP 真正想要的。相反,我确实需要提取一个子集。

我有一个非常大的字典,我想提取一个子样本,然后我想对其进行迭代。我试过了:

import random
dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = random.sample(dictionary, 3)
sample = dictionary[keys]

但它不起作用:

Traceback (most recent call last):
  File "[..]/foobar.py", line 4, in <module>
    sample = dictionary[keys]
TypeError: unhashable type: 'list'

这行得通:

import random
dictionary = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
keys = random.sample(dictionary, 3)
sample = {key: dictionary[key] for key in keys}

这似乎有点词穷:我希望有一种矢量化的方式来构建新词典。但是,这是正确/最 Pythonic 的方式吗?另外,如果我想迭代这个示例,我应该这样做:

for key, value in sample.iteritems():
    print(key, value)

我的问题不是重复的

how to randomly choose multiple keys and its value in a dictionary python

要么,因为该问题的答案并不能完全解决我的问题。它甚至比我的尝试更糟糕:它不是创建示例字典,而是对键进行采样,然后分别检索值。这显然不是很pythonic,我明确要求一个pythonic的答案。

【问题讨论】:

  • dict(random.sample(dictionary.items(), 3)) 怎么样?
  • @DeltaIV 我不能。
  • @DeltaIV 也许你会重新打开。我不会自己重新打开它,因为这可能看起来很粗略。
  • 我愿意投票支持重新开放(因为在我有机会关闭它之前就关闭了它是值得的)
  • @timgeb 问题已重新打开!请发表您的评论作为答案,我会立即接受。我实际上在我的代码中使用它。

标签: python dictionary random


【解决方案1】:

dict(random.sample(dictionary.items(), N))

您可以从字典中选择 N 随机(键、值)对并将它们传递给 dict 构造函数。

演示:

>>> import random
>>> dictionary = dict(enumerate(range(10)))
>>> dictionary
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
>>> N = 3
>>> dict(random.sample(dictionary.items(), N))
{3: 3, 6: 6, 9: 9}

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 2011-04-26
    • 1970-01-01
    • 2022-01-09
    • 2023-03-10
    • 2010-12-11
    • 2014-01-29
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多