Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a random subset of a dictionary

DISCLAIMER: I know there's a question named

Get a random sample of a dict

but mine is not a duplicate, clearly. The answers to that question mostly concentrate on computing the sum of the values a random subset of a dictionary, because that's what the OP really wanted. Instead, I really need to extract a subset.

I have a very large dictionary, and I want to extract a subsample, on which I then want to iterate. I tried:

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

But it doesn't work:

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

This works:

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}

It seems a bit word-ish: I hoped there would be a vectorized way to build the new dictionary. However, is this the right/most Pythonic way to do it? Also, if I want to iterate on this sample, should I do like this:

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

My question is not a duplicate of

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

either, because the answer to that question doesn't full address my question. It's even worse than my attempt: instead than creating a sample dictionary, it samples the keys and then retrieves the values separately. It's obviously not very pythonic, and I explicitly asked for a pythonic answer.

like image 240
DeltaIV Avatar asked Nov 02 '18 19:11

DeltaIV


People also ask

How do I fetch a specific value from a dictionary?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

How do I generate a list of values from a dictionary key?

To get the list of dictionary values from the list of keys, use the list comprehension statement [d[key] for key in keys] that iterates over each key in the list of keys and puts the associated value d[key] into the newly-created list.


1 Answers

With

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

you can select N random (key, value) pairs from your dictionary and pass them to the dict constructor.

Demo:

>>> 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}
like image 165
timgeb Avatar answered Nov 15 '22 05:11

timgeb