Osca
Osca

Reputation: 1694

Pick dictionary keys:values randomly

I want to randomly pick 1000 dictionary key, value pairs whose values is 'Zero'.

The dictionary keys are in alphabetic order at the moment. It has thousands of entries, below is part of it

[('2014','Zero'),
('2015','Zero'),
('2016','Zero')
('2017','NotZero')]

I successfully pick up 1000 'Zero' entries.

Zero = []
cnt = 0
for j in range(len(DIC)):
    if list(DIC.values())[j] == 'Zero':
        Zero.append(list(DIC.items()))
    cnt += 1
    if cnt == 1000:
        break

But I cannot find a way to randomize them. It's bias to pick the first 1000 lines because they are in alphabetic order.

Any suggestions on solving this problem? Thank you!

Upvotes: 1

Views: 141

Answers (4)

AKX
AKX

Reputation: 168957

You can use a list comprehension to get all of the keys whose matching values are Zero, then use random.sample() to choose 1000 random entries.

import random

random_keys = random.sample(
    [key for (key, value) in dic.items() if value == 'Zero'],
    1000,
)

Upvotes: 0

Teguh Hidayat
Teguh Hidayat

Reputation: 93

It can easily be done with pandas.

df = pd.DataFrame({'key': dic.keys(), 'value': dic.values()})
zeros = df.loc[df.value == 'Zero']
sample = zeros.sample(1000)

Upvotes: 1

orlp
orlp

Reputation: 117681

A dictionary does not allow for random access of elements without knowing their key. The only solution is to find all Zero elements, store them in a list, and then taking a random selection from them:

import random
zeros = [k for k, v in d.items() if v == "Zero"]
random.sample(zeros, 1000)

Upvotes: 2

Frederik.L
Frederik.L

Reputation: 5620

You can use the shuffle function:

import random

# get your zero entries

random.shuffle(Zero)

Upvotes: 0

Related Questions