简体   繁体   中英

How to save the dictionary that have tuple keys

I would like to save the dictionary having tuple on keys.

I tried pickle, ujson, json to save the dictionary. All of them did not work.

The dictionary has:

dictionary = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

I tried:

with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(dictionary)

import json
a, b, c = "abc"
data = {(1,2,3):(a,b,c), (2,6,3):(6,3,2)}
on_disk = json.dumps(data.items())

write the dictionary as string

 with open(r'test.txt','w+') as f:
     f.write(str(dictionary))

read using eval

dic = ''
with open(r'test.txt','r') as f:
         for i in f.readlines():
            dic=i #string
dic = eval(dic) # this is orignal dict with instace dict

You should use ujson , this is appropriate to address what you want. I just tried it and it works properly. If you use json you will get the following error:

TypeError: keys must be str, int, float, bool or None, not tuple

import ujson

d = {(-30, -29, -72, -71): [[-29.99867621124457, -71.75349423197208, 220], [-29.996964568219873, -71.7521560207641, 220], [-29.99696437241995, -71.7507330056961, 220], [-29.99761665426199, -71.75016101067708, 220]]}

# save dictionary
with open('depth_echo.txt', 'w') as file:
    file.write(ujson.dumps(d))

Make sure you installed ujson since it is not part of the Python standard library:

pip install ujson

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