Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON serialize a dictionary with tuples as key

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

e.g.

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

simply using json.dumps(a) raises this error:

Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/usr/lib/python2.6/json/__init__.py", line 230, in dumps     return _default_encoder.encode(obj)   File "/usr/lib/python2.6/json/encoder.py", line 367, in encode     chunks = list(self.iterencode(o))   File "/usr/lib/python2.6/json/encoder.py", line 309, in _iterencode     for chunk in self._iterencode_dict(o, markers):   File "/usr/lib/python2.6/json/encoder.py", line 268, in _iterencode_dict     raise TypeError("key {0!r} is not a string".format(key)) TypeError: key (1, 2) is not a string 
like image 852
Roberto Avatar asked Aug 09 '11 19:08

Roberto


People also ask

Can dictionaries have tuples as keys?

A tuple can never be used as a key in a dictionary.

Can you have tuples in JSON?

There is no concept of a tuple in the JSON format. Python's json module converts Python tuples to JSON lists because that's the closest thing in JSON to a tuple. Immutability will not be preserved.

How do I store a dictionary in JSON?

You can save the Python dictionary into JSON files using a built-in module json. We need to use json. dump() method to do this. Use the indent parameter to prettyPrint your JSON data.

Are tuples serializable?

Serialization and value tuplesThe ValueTuple type is not serializable in . NET Core 1.


2 Answers

You can't serialize that as json, json has a much less flexible idea about what counts as a dict key than python.

You could transform the mapping into a sequence of key, value pairs, something like this:

import json def remap_keys(mapping):     return [{'key':k, 'value': v} for k, v in mapping.iteritems()] ...  json.dumps(remap_keys({(1, 2): 'foo'})) >>> '[{"value": "foo", "key": [1, 2]}]' 
like image 173
SingleNegationElimination Avatar answered Sep 17 '22 18:09

SingleNegationElimination


from json import loads, dumps 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 s = dumps({str(k): v for k, v in x.items()})  # load in two stages: # (i) load json object obj = loads(s)  # (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.

like image 37
markling Avatar answered Sep 20 '22 18:09

markling