Reputation: 37
I am a beginner of Python. I have made a dictionary of Lists. I want to pick a random value and then to know the key of that value. Is that possible? e.g.
`lex = {"q1": [["B", "A", "C", "D"],["2" ,"D"]],
"q2": [["C", "A", "Z", "D"],["W","K"]],
"q3": [["A", "K", "D", "C"],["me", "S"]],
"q4": [["B", "L", "A", "F"],[ "1974", "D"]]}
lex_list = list(lex.values())
pick_value = random.sample(lex_list,1)`
Is there a way to know which is the key of the random value ? My purpose is to delete that pick_value from the list.Any suggestion is very much appreciated. Thank you.
Upvotes: 0
Views: 99
Reputation: 291
I understand your goal is to find the key of the random value selected and then delete it. The below code does that. Also keep in mind if there are duplicate values in your dictionary, the code will delete the first key:value pair found with that value.
In duplicates case, a list of all keys need to be found and then deleted in a separate for loop. pick_value is a nested list hence pick_value[0] works here.
The new_list generated has the pick_value deleted.
for key,value in lex.items():
if value == pick_value[0]:
lex.pop(key)
break
new_list = list(lex.values())
Upvotes: 1
Reputation: 1200
If you are interested in both the key and the value of the random pick, then why don't you consider randomly choosing one key, and gathering the value of that key?
import random
lex = {"q1": [["B", "A", "C", "D"],["2" ,"D"]],
"q2": [["C", "A", "Z", "D"],["W","K"]],
"q3": [["A", "K", "D", "C"],["me", "S"]],
"q4": [["B", "L", "A", "F"],[ "1974", "D"]]}
# Randomly pick one key
r_key = random.choice(list(lex.keys()))
# Get the value corresponding to that key
r_value = lex[r_key]
print(r_key, r_value)
This uses random.choice
to pick one element from an iterable.
This outputs:
q4 [['B', 'L', 'A', 'F'], ['1974', 'D']]
If you really would rather continue with your strategy where you already have the random value, but want the corresponding random key(s), then this might work:
import random
lex = {"q1": [["B", "A", "C", "D"],["2" ,"D"]],
"q2": [["C", "A", "Z", "D"],["W","K"]],
"q3": [["A", "K", "D", "C"],["me", "S"]],
"q4": [["B", "L", "A", "F"],[ "1974", "D"]]}
lex_list = list(lex.values())
pick_value = random.sample(lex_list,1)
# Find the corresponding key(s)
keys = [key for key, value in lex.items() if value == pick_value[0]]
print(keys)
This outputs e.g. ['q2']
. Keep in mind that I keep referring to keys as multiple, because in theory it's possible for multiple keys to correspond to the same values. If this doesn't happen in your program, then you can just take keys[0]
as your key.
The strategy uses a list comprehension to loop over the key-value pairs from lex
, and then filters on value
corresponds to pick_value
.
Again, I recommend the first strategy.
Upvotes: 1