arihant34 arihant34 -5 years ago 119
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:


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download