json serialize a dictionary with tuples as key

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

    Here is one way to do it. It will require the key to be json decoded after the main dictionary is decoded and the whole dictionary re-sequenced, but it is doable:

        import json
    
        def jsonEncodeTupleKeyDict(data):
            ndict = dict()
            # creates new dictionary with the original tuple converted to json string
            for key,value in data.iteritems():
                nkey = json.dumps(key)
                ndict[nkey] =  value
    
            # now encode the new dictionary and return that
            return json.dumps(ndict)
    
        def main():
            tdict = dict()
            for i in range(10):
                key = (i,"data",5*i)
                tdict[key] = i*i
    
            try:
                print json.dumps(tdict)
            except TypeError,e:
                print "JSON Encode Failed!",e
    
            print jsonEncodeTupleKeyDict(tdict)
    
        if __name__ == '__main__':
            main()
    

    I make no claim to any efficiency of this method. I needed this for saving some joystick mapping data to a file. I wanted to use something that would create a semi-human readable format so it could be edited if needed.

提交回复
热议问题