Q:

Write Python dictionary obtained from JSON in a file

I have this script which abstract the json objects from the webpage. The json objects are converted into dictionary. Now I need to write those dictionaries in a file. Here's my code:
#!/usr/bin/python

import requests

r = requests.get('https://github.com/timeline.json')
for item in r.json or []:
    print item['repository']['name']

There are ten lines in a file. I need to write the dictionary in that file which consist of ten lines..How do I do that? Thanks.

A:

To address the original question, something like:
with open("pathtomyfile", "w") as f:
    for item in r.json or []:
        try:
            f.write(item['repository']['name'] + "\n")
        except KeyError:  # you might have to adjust what you are writing accordingly
            pass  # or sth ..

note that not every item will be a repository, there are also gist events (etc?).
Better, would be to just save the json to file.
#!/usr/bin/python
import json
import requests

r = requests.get('https://github.com/timeline.json')

with open("yourfilepath.json", "w") as f:
    f.write(json.dumps(r.json))

then, you can open it:
with open("yourfilepath.json", "r") as f:
    obj = json.loads(f.read())

