1

I'm getting the following dict from a method:

{'patterns': {(38,): 2, (19,): 4, (9, 19): 3, (9,): 4}, 
  'rules': {(9,): ((19,), 0.75), (19,): ((9,), 0.75)}
 }

When I try to convert it to Json with json.dumps(myDict), I get the following error:

TypeError: keys must be str, int, float, bool or None, not tuple

Is there any other way I could convert it?

Many thanks!

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
Trimes
  • 21
  • 5
  • 5
    Possible duplicate of [json serialize a dictionary with tuples as key](https://stackoverflow.com/questions/7001606/json-serialize-a-dictionary-with-tuples-as-key) – hiro protagonist May 22 '19 at 12:47
  • Take a look at: https://pypi.org/project/dictfier/ – olinox14 May 22 '19 at 12:53
  • @olinox14 Thanks a lot for the tip. I had a look at it but I can't see how I can solve it with dictfier as it transforms objects to dictionaries and not the other way around. – Trimes May 22 '19 at 13:30

1 Answers1

0

json only supports string as key, so tuple-as-key isn't allowed

As @SingleNegationElimination said in his answer of a similar question:

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

However, with a little custom extension of @SingleNegationElimination's remap_keys function, you could convert your invalid dict to a valid json object.

def remap_keys(d):
    if not isinstance(d, dict):
        return d
    rslt = []
    for k, v in d.items():
        k = remap_keys(k)
        v = remap_keys(v)
        rslt.append({'key': k, 'value': v})
    return rslt

>>> remap_keys(myDict)
[{'key': 'patterns',
  'value': [{'key': (38,), 'value': 2},
            {'key': (19,), 'value': 4},
            {'key': (9, 19), 'value': 3},
            {'key': (9,), 'value': 4}]},
 {'key': 'rules',
  'value': [{'key': (9,), 'value': ((19,), 0.75)},
            {'key': (19,), 'value': ((9,), 0.75)}]}]

And you could succesfully json.dumps your dict by:

json.dumps(remap_keys(myDict))
Yuan JI
  • 2,927
  • 2
  • 20
  • 29