Reputation: 2265
I have a dictionary in Python which maps tuple to a number as follows.
The goal is to have my data printed in pretty json format, but I am getting an error
import json
data = {
(7, 0, 4, 1, 0, 0, 3): 2,
(7, 0, 3, 1, 0, 0, 3): 1,
(2, 0, 0, 1, 0, 0, 1): 3,
(7, 0, 2, 1, 0, 0, 3): 4,
(7, 0, 4, 1, 0, 0, 2): 1,
(0, 0, 0, 0, 0, 0, 0): 2,
}
print (json.dumps(data))
I am getting an error
return _iterencode(o, 0)
TypeError: keys must be a string
Apparently it has something to do with the tuple.
Casting data to string does not work, it only returns one-line result.
"{(7, 0, 4, 1, 0, 0, 3): 2, (7, 0, 3, 1, 0, 0, 3): 1, (2, 0, 0, 1, 0, 0, 1): 3, (7, 0, 2, 1, 0, 0, 3): 4, (7, 0, 4, 1, 0, 0, 2): 1, (0, 0, 0, 0, 0, 0, 0): 2}"
Upvotes: 0
Views: 1679
Reputation: 18914
keys in json must be strings. Try this:
print (json.dumps(({str(k):v for k,v in data.items()})))
You can also use indent to make it prettier:
print (json.dumps(({str(k):v for k,v in data.items()}),indent=2))
Upvotes: 2