jeudi 20 avril 2023

return a series of keys based on value python randomly generated in separate line

I'm trying to return a series of values when randomly generating a number which then corresponds to a certain key.

This is a miniature version of my dictionary (key = word, value = character count) :


import random

myDict = {
"lire": "4",
"l'art": "5",
"écrire": "6",
"écouter": "7",
"compter": "7",
"répéter": "7",
"étudier": "7",
"aller à": "7",
"calculer": "8",
"regarder": "8"}

I tried two options.

1)

def search(myDict, lookup):
    for key, value in myDict.items():
        for v in value:
            if lookup in v:
                return key

print(search(myDict, str(random.randint(4,10)))
    print([k for k, v in myDict.items() if v == 'random.randint(4,10)'])
    

    Both options work when the value is "4" and print lire or ['lire'] respectively. However, when the value is 4 (without quotation marks) or random.randint(4,10) or 'random.randint(4,10)', it returns [].

    The value seemingly has to be a string but if I search for the random function in '' then it obviously does not return a key because none of the values are called 'random.randint(4,10)'.

    If someone could find a solution where I can link the two sections (randomly generated number and valid set of keys from random value), that would be great. Thank you.




    Aucun commentaire:

    Enregistrer un commentaire