arihant34 arihant34 - 10 months ago 24
Python Question

How to read dictionaries in python?

I have a file of name "input.txt". In this text file a lot of dictionaries are stored. I have to iterate through these dictionaries. How do read the file? Whenever I read the file using open(), it coverts the whole text into a string type. How to read this file as collection of dictionaries?

Contents of input.txt:



Use the json module's method to convert loaded str to dict for each line in the file:

import json

with open('input.txt','r') as f:
    for line in f.readlines():
        line_as_dict = json.loads(line)
        # process here the dict