python - How to select json data randomly -
i have following json file , need way randomly select json data , prints value.
json file :
{ "base": [{"1": "add"},{"2": "act"}], "past": [{"add": "added"},{"act": "acted"}], "past-participle": [{"add": "added"},{"act": "acted"}], "s-es-ies": [{"add": "adds"},{"act": "acts"}], "ing": [{"add": "adding"},{"act": "acting"}] }
example
user_input = 'past' >> past code randomly selects 'add' or 'act' past >> add prints out value >> added
use random.choice
supplying choices sequence contained selected key
:
user_input = input('> ') > past list(choice(j[user_input]).values())[0] out[177]: 'added'
factor in function make more compact:
def random_json_val(json_obj, k): return list(choice(json_obj[k]).values())[0]
calling gets random value given k
:
>>> random_json_val(j, 'past') 'added' >>> random_json_val(j, 'past') 'acted' >>> random_json_val(j, 's-es-ies') 'acts'
Comments
Post a Comment