json serialize a dictionary with tuples as key

前端 未结 6 1872
走了就别回头了
走了就别回头了 2020-12-05 09:27

Is there a way in Python to serialize a dictionary that is using a tuple as key:

a={(1,2):\'a\'}

simply using json.dumps(a), produces:

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 09:53

    from json import load, dump
    from ast import literal_eval
    
    x={ (0,1):'la-la la', (0,2):'extricate' }
    
    # save: convert each tuple key to a string before saving as json object
    with open('/tmp/test', 'w') as f: dump({str(k):v for k, v in x.items()}, f)
    
    # load in two stages:#
    # (i) load json object
    with open('/tmp/test', 'r') as f: obj = load(f)
    
    # (ii) convert loaded keys from string back to tuple
    d={literal_eval(k):v for k, v in obj.items()}
    

    See: https://stackoverflow.com/a/12337657/2455413

提交回复
热议问题