In [1]:
from __future__ import print_function

import json

Save to file

Create data and save it to file


In [2]:
data = {
    'one': 1, 
    'two': 2, 
    'list': [1, 2, 3, 4], 
    'matrix': [[1, 2, 3], [4, 5, 6], [7, 8, 9]], 
    'float_list': [1.0, 2.0], 
    'dict': {
        'one': 4, 
        'two': 5, 
        'dict': {
            'list': [0, 1, 2, 8]
        }
    }
}

json.dump(data, open('data.json', 'w'), indent=2, sort_keys=True)

Iteration


In [4]:
for kk, vv in data.items(): 
    print('  The key is:', kk)
    print('The value is:', vv)
    print()


  The key is: one
The value is: 1

  The key is: two
The value is: 2

  The key is: list
The value is: [1, 2, 3, 4]

  The key is: matrix
The value is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

  The key is: float_list
The value is: [1.0, 2.0]

  The key is: dict
The value is: {'one': 4, 'two': 5, 'dict': {'list': [0, 1, 2, 8]}}

Iterate over the elements of the matrix


In [5]:
for row in data['matrix']: 
    for el in row: 
        print(el, end=' ')
    print()


1 2 3 
4 5 6 
7 8 9 

 Random access

Randomly access various regions of the dictionary


In [6]:
data['matrix'][0][0] += 1000
print(data['matrix'])


[[1001, 2, 3], [4, 5, 6], [7, 8, 9]]

In [7]:
data['dict']['dict']


Out[7]:
{'list': [0, 1, 2, 8]}

In [8]:
data['dict']['dict']['list'][2]


Out[8]:
2

 Load dictionary from file


In [9]:
data_2 = json.load(open('data.json', 'r'))
print(json.dumps(data, indent=2, sort_keys=True))
print(json.dumps(data_2, indent=2, sort_keys=True))


{
  "dict": {
    "dict": {
      "list": [
        0,
        1,
        2,
        8
      ]
    },
    "one": 4,
    "two": 5
  },
  "float_list": [
    1.0,
    2.0
  ],
  "list": [
    1,
    2,
    3,
    4
  ],
  "matrix": [
    [
      1001,
      2,
      3
    ],
    [
      4,
      5,
      6
    ],
    [
      7,
      8,
      9
    ]
  ],
  "one": 1,
  "two": 2
}
{
  "dict": {
    "dict": {
      "list": [
        0,
        1,
        2,
        8
      ]
    },
    "one": 4,
    "two": 5
  },
  "float_list": [
    1.0,
    2.0
  ],
  "list": [
    1,
    2,
    3,
    4
  ],
  "matrix": [
    [
      1,
      2,
      3
    ],
    [
      4,
      5,
      6
    ],
    [
      7,
      8,
      9
    ]
  ],
  "one": 1,
  "two": 2
}

In [ ]:


In [ ]: