1

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?

2
  • you can't with json. Use python dict repr + ast.literal_eval Commented Jun 20, 2018 at 13:31
  • @Jean-FrançoisFabre Thank you -- hadn't seen that question. Will refer to that! Commented Jun 20, 2018 at 13:35

1 Answer 1

1

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

dict = {int(k):v for k,v in dict.items()}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.