Skip to content

Instantly share code, notes, and snippets.

@dunderrrrrr
Created February 21, 2020 13:43
Show Gist options
  • Save dunderrrrrr/a3b36a8ec6d503700c34b827ed9a58ca to your computer and use it in GitHub Desktop.
Save dunderrrrrr/a3b36a8ec6d503700c34b827ed9a58ca to your computer and use it in GitHub Desktop.
In Python, a nested dictionary is a dictionary inside a dictionary.

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of dictionaries into one single dictionary. More reading here.

Sometimes you need to build nested dicts. This can be frustrating to get right. Here's an example.

...
if r.status_code == 200:
    result = r.json()
    c = 0
    data = {'repos': {}}
    for res in result:
        data['repos'][c] = {}
        data['repos'][c]['name'] = res['full_name']
        data['repos'][c]['desc'] = res['description']
        data['repos'][c]['language'] = res['language']
        data['repos'][c]['forks'] = res['forks']
        data['repos'][c]['watchers'] = res['watchers']
        data['repos'][c]['stars'] = res['stargazers_count']
        data['repos'][c]['dates'] = {}
        data['repos'][c]['dates']['created_at'] = res['created_at']
        data['repos'][c]['dates']['updated_at'] = res['updated_at']
        data['repos'][c]['dates']['pushed_at'] = res['pushed_at']
        c = c+1
    json_object = json.dumps(data, sort_keys=False)
    return(json_object)
...

Output

{
  "repos": {
  [...]
    "10": {
        "name": "dunderrrrrr/Pi-hole-FastAPI",
        "desc": "An FastAPI for Pi-hole",
        "language": "Python",
        "forks": 0,
        "watchers": 4,
        "stars": 4,
        "dates": {
            "created_at": "2019-11-20T13:29:19Z",
            "updated_at": "2020-01-25T22:47:50Z",
            "pushed_at": "2019-11-20T13:35:30Z"
        }
    },
    "11": {
        "name": "dunderrrrrr/vsphereapi",
        "desc": "Connect to VMWare REST API and get VM data",
        "language": "Python",
        "forks": 1,
        "watchers": 0,
        "stars": 0,
        "dates": {
            "created_at": "2019-02-19T19:54:56Z",
            "updated_at": "2019-02-23T11:49:38Z",
            "pushed_at": "2019-10-21T15:47:54Z"
        }
    },
    [...]
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment