python字符串生成字典_从字典字符串生成词典

另一个安全函数是使用JSON。这里我使用json.dump()和json.load()函数。唯一的障碍是json load将字符串作为unicode字符串返回,因此我使用自己的jsondeconder类,该类调用super,然后遍历结果对字符串进行编码:import json

from types import *

# your own decoder class to convert unicode to string type

class MyJSONDecoder(json.JSONDecoder):

# decode using our recursive function

def decode(self,json_string):

return self._decode_obj(super(MyJSONDecoder,self).decode(json_string))

# recursive function to traverse lists

def _decode_list(self,data):

decoded = []

for item in data:

if type(item) is UnicodeType: item = item.encode('utf-8')

elif type(item) is ListType: item = self._decode_list(item)

elif type(item) is DictType: item = self._decode_obj(item)

decoded.append(item)

return decoded

# recursive function to traverse objects

def _decode_obj(self,data):

decoded = {}

for key, value in data.iteritems():

if type(key) is UnicodeType: key = key.encode('utf-8')

if type(value) is UnicodeType: value = value.encode('utf-8')

elif type(value) is ListType: value = self._decode_list(value)

elif type(value) is DictType: value = self._decode_obj(value)

decoded[key] = value

return decoded

# the dictionary to save

dict = {

"123": 2,

"125": 4,

"126": 5,

"128": 6

}

# decoder instance

my_decoder = MyJSONDecoder()

# write object to file

with open('serialized.txt', 'w') as new_file:

json.dump(dict, new_file)

new_file.close()

print "Original", dict

# read object from file

with open ("serialized.txt", "r") as old_file:

dictcopy = my_decoder.decode(old_file.read())

old_file.close()

print "**Copy**", dictcopy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值