In researching the answer to this question here on stackoverflow, I’ve learned a lot of new things, but have so far been unable to close the deal.
My python process will be receiving one line of input via stdin, e.g.
[{'name':'ry', 'age':28}, {'name':'bo', 'age':11}, {'name':'ed', 'age':99}]
…and I’d like to be able to store this line directly to a list object that I can then iterate over, e.g.
for i in list:
print i['age'], i['name']
…but I just cannot get this to work, whether I use sys.stdin() or the fileinput module. For example, even when I explicitly create a list with x = list(stdin.readline()) it ends up making each character a separate item in the list, not parsing the text in the way I want it to. Anyway.. back to searching. (Thanks for reading.)
A bad way is to use
input. However this is unsafe and the function has been removed in Python 3 (the function calledinputin Python 3 does the same as Python 2’sraw_input).A better way is to use
ast.literal_eval.See it working online: ideone