json serialize a dictionary with tuples as key

前端 未结 6 1858
走了就别回头了
走了就别回头了 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:47

    json can only accept strings as keys for dict, what you can do, is to replace the tuple keys with string like so

    with open("file", "w") as f:
        k = dic.keys() 
        v = dic.values() 
        k1 = [str(i) for i in k]
        json.dump(json.dumps(dict(zip(*[k1,v]))),f) 
    

    And than when you want to read it, you can change the keys back to tuples using

    with open("file", r) as f:
        data = json.load(f)
        dic = json.loads(data)
        k = dic.keys() 
        v = dic.values() 
        k1 = [eval(i) for i in k] 
        return dict(zip(*[k1,v])) 
    

提交回复
热议问题