How to Get a Random Value from Dictionary

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

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

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 generate a random dictionary?

Just default all the values to value1 first, and then randomly pick one key to change to value2:

def function(n):
from random import randrange
values = ['value1', 'value2']
mydict = {"key " + str(i): values[0] for i in range(n)}
mydict["key " + str(random.randrange(n))] = values[1]

return mydict

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.

Generating random numbers as the value of dictionary in python

I think what you want is something like:

{k: random.random() for k in range(100)}


Related Topics



Leave a reply



Submit