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.
Advertisement
Answer
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())