I have this list that randomly will choose a different value each time, how can I print the key of the random value that is being selected separately?
import random
a_dictionary = {"winter": 10, "summer": 30,"spring":20,"autumn":15}
values = list(a_dictionary.values())
key = list(a_dictionary.keys())
randomx= random.choice( values)
print(randomx)
#print(randomx.key)
example: random value =
20
spring
CodePudding user response:
Try using .items()
import random
a_dictionary = {"winter": 10, "summer": 30,"spring":20,"autumn":15}
print(random.choice(list(a_dictionary.items()))) # prints ('winter', 10)
CodePudding user response:
Perhaps you could try:
key, value = random.choice(list(a_dictionary.items()))
Alternatively, if you have no control over the process that does the choice picking (i.e. you just have the value), you can use a reverse dict:
rev_dict = {v: k for k, v in a_dictionary.items()}
# and later, say your randomx is 20
>>> rev_dict[randomx]
'spring'
CodePudding user response:
This should work.
import random
dict = {
"winter" : 10,
"summer" : 30,
"spring": 20,
"autumn" : 15
}
values = list(dict.values())
keys = list(dict.keys())
random = random.choice(values)
print(random)
print(keys[values.index(random)])
CodePudding user response:
You don't have to iterate over the list of VALUES, but over the list of ITEMS:
season, number = random.choice(list(a_dictionary.items()))