Best way to encode tuples with json

后端 未结 5 1857
有刺的猬
有刺的猬 2021-02-05 00:23

In python I have a dictionary that maps tuples to a list of tuples. e.g.

{(1,2): [(2,3),(1,7)]}

I want to be able to encode this data use it with j

5条回答
  •  再見小時候
    2021-02-05 00:57

    If your key tuples are truly integer pairs, then the easiest and probably most straightforward approach would be as you suggest.... encode them to a string. You can do this in a one-liner:

    >>> simplejson.dumps(dict([("%d,%d" % k, v) for k, v in d.items()]))
    '{"1,2": [[2, 3], [1, 7]]}'
    

    This would get you a javascript data structure whose keys you could then split to get the points back again:

    '1,2'.split(',')
    

提交回复
热议问题