There was a need to save data format: a dictionary from a pair to a list of pairs. I am writing in Python3.

I wanted to use json, but unfortunately he does not understand the tuple and gives an error

TypeError: keys must be a string .

Tell me, in what format can you save this type of data to a file?

  • one
    For example in Pickle ... you for what purpose should be saved? Should the file be "human readable" ? - MaxU

1 answer 1

You can use YAML (if you need a file that you can open in the editor and see the values):

 In [132]: import yaml In [133]: d = {(0.5, 0.5): list('1011'), (2, 2): list('0000'), (1, 1): list('1001')} In [134]: d Out[134]: {(0.5, 0.5): ['1', '0', '1', '1'], (1, 1): ['1', '0', '0', '1'], (2, 2): ['0', '0', '0', '0']} In [135]: with open('c:/temp/out.yml', 'w') as f: ...: yaml.dump(d, f, indent=4) ...: 

Result:

 ? !!python/tuple [0.5, 0.5] : ['1', '0', '1', '1'] ? !!python/tuple [1, 1] : ['1', '0', '0', '1'] ? !!python/tuple [2, 2] : ['0', '0', '0', '0'] 

Reading from YAML:

 In [136]: with open('c:/temp/out.yml') as f: ...: new = yaml.load(f) ...: In [137]: new Out[137]: {(0.5, 0.5): ['1', '0', '1', '1'], (1, 1): ['1', '0', '0', '1'], (2, 2): ['0', '0', '0', '0']} 

or Pickle (the file will be binary - it will be difficult to see the values ​​in the editor;):

 In [146]: import pickle In [147]: with open('c:/temp/out.pickle', 'wb') as f: ...: pickle.dump(d, f) ...: In [148]: with open('c:/temp/out.pickle', 'rb') as f: ...: d2 = pickle.load(f) ...: In [149]: d2 Out[149]: {(0.5, 0.5): ['1', '0', '1', '1'], (1, 1): ['1', '0', '0', '1'], (2, 2): ['0', '0', '0', '0']}