Saving dictionary whose keys are tuples with json, python

前端 未结 4 2543
醉话见心
醉话见心 2021-02-20 10:37

I am writing a little program in python and I am using a dictionary whose (like the title says) keys and values are tuples. I am trying to use json as follows

im         


        
4条回答
  •  孤街浪徒
    2021-02-20 11:03

    If you want to load your data later on you have to postprocess it anyway. Therefore I'd just dump data.items():

    >>> import json
    >>> a, b, c = "abc"
    >>> data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
    >>> on_disk = json.dumps(data.items())
    >>> on_disk
    '[[[2, 6, 3], [6, 3, 2]], [[1, 2, 3], ["a", "b", "c"]]]'
    >>> data_restored = dict(map(tuple, kv) for kv in json.loads(on_disk))
    >>> data_restored
    {(2, 6, 3): (6, 3, 2), (1, 2, 3): (u'a', u'b', u'c')}
    

提交回复
热议问题