Random Entry from Dictionary

How to get a random value from dictionary?

One way would be:

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.values()))

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()))

Random entry from dictionary

Updated to use generics, be even faster, and with an explanation of why this option is faster.

This answer is similar to the other responses, but since you said you need "a number of random elements" this will be more performant:

public IEnumerable<TValue> RandomValues<TKey, TValue>(IDictionary<TKey, TValue> dict)
{
Random rand = new Random();
List<TValue> values = Enumerable.ToList(dict.Values);
int size = dict.Count;
while(true)
{
yield return values[rand.Next(size)];
}
}

You can use this method like so:

Dictionary<string, object> dict = GetDictionary();
foreach (object value in RandomValues(dict).Take(10))
{
Console.WriteLine(value);
}

This has performance improvements over the other responses (including yshuditelu's response).

  1. It doesn't have to create a new collection of all of the dictionary's elements each time you want to fetch a new random value. This is a really big deal if your dictionary has a lot of elements in it.
  2. It doesn't have to perform a lookup based on the Dictionary's key each time you fetch a random value. Not as big a deal as #1, but it's still over twice as fast this way.

My tests show that with 1000 objects in the dictionary, this method goes about 70 times faster than the other suggested methods.

How to pick one key from a dictionary randomly

To choose a random key from a dictionary named my_dict, you can use:

random.choice(list(my_dict))

This will work in both Python 2 and Python 3.

For more information on this approach, see: https://stackoverflow.com/a/18552025

How to get a random element from a python dictionary?

You can use the items method to get the pairs, then transform it to a list that supports indexing:
random.choice(list(country.items()))

Get random element of dictionary in TypeScript?

Here you go. I use the dictionary you created and randomly select a number based on the length of the dictionary (which are your keys). Then return the value of the random key.

Here is for Typescript (test in https://www.typescriptlang.org/play):

var dict: {[key: number]: string} = {
0: "example 1",
1: "example 2",
2: "example 3"
}

function randomGen() {
var value = dict[Math.floor(Math.random() * Object.keys(dict).length)];
return value;
}

console.log(randomGen());

And below is for basic JavaScript:

var dict = {
0: "example 1",
1: "example 2",
2: "example 3"
}

function randomGen() {
var value = dict[Math.floor(Math.random() * Object.keys(dict).length)];
return value;
}

console.log(randomGen());

How to randomly select an item from a dictionary?

random.choice takes a list (or tuple) in input (it needs integer-indexable objects).

So just convert rank dictionary (the values, it is) to a list then pick a value: like this (I've created a new function because the rank(rank) bit made no sense, you don't need a parameter to pick a card:

# globally defined (constant), pointless to define it locally, you may
# need it in another part of the program
rank={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'Jack':10,
'King':10,'Queen':10,'Ace':1}

def pick():
return random.choice(list(rank.values()))

list(rank.values()) is required in python 3, dictionary values are no longer of list type. Maybe you want to pre-compute this list to save computation time.

Get A Random Value from dictionary in Python

It's not really clear how you want to simulate a deck with this dict.

If you just use random.choice multiple times, you might get the same card twice, which probably shouldn't happen.

You could create a whole deck (as a list, not as a dict), shuffle it, draw a card (thus removing it from the deck), and check its value.
Defining a new Card class isn't too hard with namedtuple, and it will make it easier to work with afterwards (Thanks to @MaartenFabré for the comment):

# encoding: utf-8
import random
from collections import namedtuple

class Card(namedtuple('Card', ['face', 'color'])):
colors = ['♠', '♥', '♦', '♣']
faces = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = dict(zip(faces, [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]))

def __repr__(self):
return self.face + self.color

def value(self):
return Card.values[self.face]

@staticmethod
def all():
return [Card(face, color)
for color in Card.colors for face in Card.faces]

deck = Card.all()

print(deck)
# ['A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠', 'A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣']

random.shuffle(deck)

print(deck)
# ['9♣', '4♠', 'J♥', '9♦', '10♠', 'K♣', '8♥', '3♣', 'J♣', '10♦', '8♦', 'A♣', '7♦', '3♠', '7♠', 'Q♣', '7♥', 'Q♦', 'A♦', '9♥', '2♠', '7♣', '6♦', '4♣', 'Q♠', '3♥', 'K♠', '6♣', '5♦', '4♥', '5♣', '2♣', '2♥', '6♥', '8♠', '2♦', '4♦', '8♣', 'K♦', '10♥', 'K♥', '5♠', 'J♦', '5♥', 'A♥', '9♠', '6♠', 'Q♥', '10♣', 'A♠', '3♦', 'J♠']

a_card = deck.pop()
print(a_card)
# J♠
print(a_card.face)
# J
print(a_card.color)
# ♠
print(a_card.value())
# 10

Python - How to randomly choose items from hash?

Randomize the random choice again!

import random

def get_random_element():
first = dict(a=1, b=2)
second = dict(a=2, b=3, c=4, d=6, )
return [first, second]

# choose a random dict
choice = random.choice(get_random_element())
# choose some random keys, and generate the selected values
elements = {sample: choice.get(sample) for sample in random.sample(list(choice), random.randint(1, len(choice)))}
print(elements)


Related Topics



Leave a reply



Submit