简体   繁体   中英

Reading dictionary from text file converts integer keys to string: Python

I have a file which contains string from json.dumps(d) where d is a dictionary originally created as:

   >> d = {1: [1,2,3], 2:[5,6,7], 3:[7,8,9]} # integer keys

When I open this file and get the dictionary into RAM:

  >> d = json.loads(open('file.txt', 'r').read())
  >> d[1]
   ## Gives error
  >> d['1']
   ## doesn't give error

Am I doing something wrong in saving my dictionary?

No, you're misunderstanding JSON. Names in a JSON object must be strings; they cannot be any other type even if the programming language being used can support them. If you want them to not be strings after decoding then you need to implement additional parsing in a separate decoder. Consider using json.JSONDecoder 's object_hook or object_pair_hook arguments.

This is completely normal. Only arrays in json strings can be invoked by position(integer as you call it). In your case. If you look at the output of json.dumps({1: [1,2,3], 2:[5,6,7], 3:[7,8,9]}) you will see that you get {"1": [1, 2, 3], "2": [5, 6, 7], "3": [7, 8, 9]} . Hence the string keys when you try to access the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM