user7649012
user7649012

Reputation: 23

Random values from list of tuples in python

I am trying to get some random 5 or 8 values from the following type of input in python

[(1, (0.0, 1.1)), (2, (0.0, 2.21)), (3, (0.0, 3.31)), (5, (0.0, 4.41)), 
(5,(0.0, 5.51)), (6, (0.0, 6.62)), (7, (0.0, 7.72)), (8, (0.04, 0.0)), 
(9, (0.04, 1.1)), (10, (0.04, 2.21)), (11, (0.04, 2.21)), (12, (0.04, 3.31)), 
(13, (0.04, 3.31)), (14, (0.04, 4.41))]

How can i approach to get that?

Upvotes: 2

Views: 91

Answers (2)

dmlicht
dmlicht

Reputation: 2438

First off, as several commenters mentioned, the input you posted on your question is a list of tuples, not a dict. That aside, to take a random value from a collection you can use: random.choice, random.sample or random.choices from the python standard library.

You can call the functions like so:

import random
your_input = [(1, (0.0, 1.1)), (2, (0.0, 2.21)), (3, (0.0, 3.31)),
              (5, (0.0, 4.41)), (5,(0.0, 5.51)), (6, (0.0, 6.62)),
              (7, (0.0, 7.72)), (8, (0.04, 0.0)), (9, (0.04, 1.1)),
              (10, (0.04, 2.21)), (11, (0.04, 2.21)), (12, (0.04, 3.31)), 
              (13, (0.04, 3.31)), (14, (0.04, 4.41))]

# Let's take one random number
one_choice = random.choice(your_input)

# Let's sample 10 random numbers from the list without replacement
n_samples = random.sample(your_input, k=10)

# Let's take 10 random numbers from the list **with** replacement
n_samples = random.choices(your_input, k=10)

Upvotes: 1

MSeifert
MSeifert

Reputation: 152657

First you need to convert your list of tuples to a dictionary:

l = [(1, (0.0, 1.1)), (2, (0.0, 2.21)), (3, (0.0, 3.31)), (5, (0.0, 4.41)), 
(5,(0.0, 5.51)), (6, (0.0, 6.62)), (7, (0.0, 7.72)), (8, (0.04, 0.0)), 
(9, (0.04, 1.1)), (10, (0.04, 2.21)), (11, (0.04, 2.21)), (12, (0.04, 3.31)), 
(13, (0.04, 3.31)), (14, (0.04, 4.41))]

d = dict(l)

To get 8 random keys use random.sample:

import random
randomkeys = random.sample(d.keys(), 8)

To get the corresponding values you could use operator.itemgetter:

import operator
randomvalues = operator.itemgetter(*randomkeys)(d)

Upvotes: 0

Related Questions