0

I have a file that contains multiple dictionaries such that, newfile = {"votes": {"funny": 0, "useful": 5, "cool": 2}, "user_id": "rLtl8ZkDX5vH5nAx9C3q5Q", "review_id": "fWKvX83p0-ka4JS3dc6E5A", "stars": 5, "date": "2011-01-26"} {"votes": {"funny": 0, "useful": 0, "cool": 0}, "user_id": "0a2KyEL0d3Yb1V6aivbIuQ", "review_id": "IjZ33sJrzXqU-0X6U8NwyA", "stars": 5, "date": "2011-07-27"} This file is stored in my drive, i need to read each record line by line from file and want to print values for each key such as,

print newfile['votes'] = {"funny": 0, "useful": 5, "cool": 2} for first line
print newfile['votes'] = {"funny": 0, "useful": 0, "cool": 0} for second line

1 Answers1

1

First, read the file line by line, such as here: https://stackoverflow.com/a/3277512/141789

Then, parse the text as json strings (presuming the individual lines are in valid json format, if not your problem has become much more difficult).

import json
dicts = []
for line in array:
    dicts.append(json.loads(line))

If the entire file is in json format it's much easier. In that case it would look like [{...},{...}]. I.e the dictionaries are enclosed within square brackets (list of dictionaries) and separated by a comma.

Just look for "read from json" and you'll find tons of examples of how this can be read

Karl
  • 5,573
  • 8
  • 50
  • 73