1

I am trying to write a Python dictionary to a file in json notation. That is how I have tried that:

def write_to_json(self, data):
  with open('dict.json', 'w') as file:
    json.dump(data, file)

However, the dump method fails for my dictionary. It says:

TypeError: key 23 is not a string

This is (indeed) correct, it should be Integer, but because the data is orginally read from a csv file and gets manipulated, I cannout guarantee so I need to convert them.

How can I convert each item in a dicitonary (key as well as the values) into a string?

Here is how an example of the dictionary looks like (its basically key -> list):

{1: [5,6,8,6], 2: [7,8,9]...}
Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100
ItFreak
  • 2,299
  • 5
  • 21
  • 45

3 Answers3

1
newdict = { str(k):str(v) for k,v in olddict.items() }

or, without even saving it to an intermediate variable:

json.dump( { str(k):v for k,v in data.items() }, file )

This converts only the keys (which is all that JSON really needs - JSON values can be integers or other things as well).

If you need to convert all data, it may be better to do that before constructing the dictionary from the input data, but if that's not an option, this should work (ONLY if the data is exactly as you show it, note that making a converter that will find any integer in a nested structure and convert it to a string is also possible, but a bit more involved):

json.dump( { str(k):[str(i) for i in v] for k,v in data.items() } )

(this assumes that each value in the dictionary is an array of integers or strings)

Leo K
  • 5,189
  • 3
  • 12
  • 27
1

This should do what you want in python 2

json.dump({str(k): map(str, v) for k, v in data.iteritems()}, file)

and python 3

json.dump({str(k): list(map(str, v)) for k, v in data.items()}, file)

Note that an easy way to check this works is to use the json.dumps method as a test for example

In [489]: data = {1: [5,6,8,6], 2: [7,8,9]}

In [490]: json.dumps({str(k): map(str, v) for k, v in data.iteritems()})
Out[490]: '{"1": ["5", "6", "8", "6"], "2": ["7", "8", "9"]}'
Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100
0
{str(k): [str(x) for x in v] for k, v in array.items()}

Result

>>> {str(k) : [str(x) for x in v] for k, v in a.items()}
{'1': ['1', '2', '3'], '2': ['1', '2']}