#๐ how do I use random with a dictionary
33 messages ยท Page 1 of 1 (latest)
@tall agate
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.
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).
not really; were your test sample's keys 0, 1... :p
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)
ahhh
I tried that
dont work
sadly
What is in your dictionary? Is each card a dictionary? And do you have a "deck" which is a list of card dictionaries?
I have a deck
Is your deck a list?
no its a dictionary
What doe the first few items look like?
deck = {"face cards":10,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"ten":10,"ace":"ace"}
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.
Not allowed by your teacher? Have you studied lists and dictionaries?
its not by my teacher is was by my friends he wanted me to try this in this way
but Im stuck
and I have studied lists and dictionaries
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.
my bad that was what he meant
Im a bit slow
OK. Good!
Ha, they were actually. My bad.
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