How to get random value from a file in python? -
it have been gratifying figure out myself haven't been able to.
i want grab random value text file contains data in form of dictionary eg:
{'one': '1111111', 'two': '2222222', 'three': '3333333'}
i've tried few variations, code currently:
from random import * table = open('file.txt') random_value = random.choice(table.values())
when try , print 'random_value' (to see if working), error:
attributeerror: 'file' object has no attribute 'values'
table
file object, , want turn dictionary. here use ast
module:
from random import choice # no need import if you're going use 1 function import ast table = open('file.txt').read() mydict = ast.literal_eval(table) random_value = choice(mydict.values())
Comments
Post a Comment