#๐Ÿ”’ how do I use random with a dictionary

33 messages ยท Page 1 of 1 (latest)

static valleyBOT
#

@tall agate

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

eager spade
#

The easiest way would probably be just to use the keys/values/items method, and get a random element from there.

#

Wait, you can call choice directly on dictionaries (I apparently haven't tried that in a long time).

jagged flower
#

choice expects its argument to quack like a Seq

#

to answer the Q: you can listify the keys of your dictionary, run random.choice over that to get a random key, then, if needed, query the corresponding value from your dictionary as well

#

there is no way to directly sample from a dictionary (well unless your keys happen to be 0, 1 ... N-1, which is unreliable to say the least ig)

tall agate
#

ahhh

solid rampart
#

What is in your dictionary? Is each card a dictionary? And do you have a "deck" which is a list of card dictionaries?

solid rampart
#

Is your deck a list?

tall agate
solid rampart
#

What doe the first few items look like?

tall agate
#

deck = {"face cards":10,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"ten":10,"ace":"ace"}

solid rampart
#

I can suggest an alternative. Make each card a dictionary, with maybe a rank, value, suit, etc. Then create a deck which is a list of card dictionaries. Given that, then you can easily choose a random element (a card) from the deck.

tall agate
#

like make all of them there on dictionaries is not allowed

#

idk why

#

I asked

solid rampart
#

Not allowed by your teacher? Have you studied lists and dictionaries?

tall agate
#

but Im stuck

#

and I have studied lists and dictionaries

solid rampart
#

Well, please tell your friend, that to do the problem correctly, a list of dictionaries is the proper solution. This allows you to pick a random card (dictionary) from the deck (list). In fact, it also allows you to "shuffle" the deck in a single line, and therefore, be able to deal out cards in a random order.

tall agate
#

Im a bit slow

solid rampart
#

OK. Good!

eager spade
static valleyBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

๐Ÿ”’ how do I use random with a dictionary