1

I'm trying to dump a dictionary to a json file using the code below:

import json
with open('save.json', 'w') as outfile:
    json.dump({
        (0, 0): 0,
        (0, 1): 1,
        (1, 0): 0,
        (1, 1): 1,
    }, outfile)

But I'm having an issue with using tuples as keys. This works when I define a dictionary, but when I try to dump it to a file it gives this error:

TypeError: key (0, 0) is not a string

I'm using Python 3 on a linux based machine.

Any help fixing this would be appreciated.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114

1 Answers1

2

JSON standard requires keys being strings. If your purpose is saving this dictionary into a file - consider using pickle module:

import pickle
with open('save.json', 'w') as outfile:
    pickle.dump({
        (0, 0): 0,
        (0, 1): 1,
        (1, 0): 0,
        (1, 1): 1,
    }, outfile)
reartnew
  • 247
  • 1
  • 9