0

I have saved a dictionary as json to re-use later across a number of areas.

The dictionary structure is:

dict = {
    1: 'Name',
    2: 'Name2',
    3: 'Name3'
}

I have saved it as so:

with open('fpath', 'w') as out :
    json.dump(dict, out)

When I am reading it back in, though, it reads the dictionary keys as strings, not ints, as follows:

with open('fpath', 'r') as inf :
    dict = json.load(inf)

print (dict)

dict = {
    '1': 'Name',
    '2': 'Name2',
    '3': 'Name3'
}

This makes it so I can't use it as needed, for example to map it to a pandas dataframe column.

How do I save the dictionary so that the keys are saved and read back in as ints, not strings?

jbachlombardo
  • 141
  • 2
  • 13

1 Answers1

1

I suggest you to post-process the dict with the following line:

dict = {int(k):v for k,v in dict.items()}
Laurent H.
  • 6,316
  • 1
  • 18
  • 40