1. 程式人生 > >python有序的字典

python有序的字典

ont author sof exceptio encode int clas bin pytho

python中有序的字典 OrderedDict

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/10/13 09:45
# @Author : wlgo2108
# @Site :
# @File : readmsg.py
# @Software: PyCharm
# @Email : [email protected]


import configparser
from collections import OrderedDict


def read_msg(filename,encoding = "gb2312"):
"""
將後臺交易的報文轉換成字典返回
:param filename:
:param encoding:
:return:
"""
tran_code = None
value_dict = OrderedDict()
try:
tran_code = str(filename).replace("T","")[0:6]
conf = configparser.ConfigParser()
conf.read(filename, encoding=encoding)
sects = conf.sections()
for sect in sects:
options = conf.options(section=sect)
for option in options:
if "name" in option:
value = conf.get(sect, option)
value = str(value.encode(encoding).split("#")[0]).replace("\t", "")
for i in range(0, len(value)):
if value.isupper():
value_dict[value.lower()] = value.lower()
break
elif ord(value[i]) >= 65 and ord(value[i]) <= 91:
if i != 0:
value = str(value).replace(value[i], "_%s" % (str(value[i]).lower()))
value_dict[value.lower()] = ""
print value
except Exception as e:
print(e)
return tran_code,value_dict


def list_to_dict(lst_value = [],dict_re = {}):
"""
將列表的值賦值給字典,要保證元素長度一致。
:param lst_value:
:param dict_re:
:return:
"""
if len(lst_value) == len(dict_re):
for i in range(0,len(lst_value)):
dict_re[dict_re.keys()[i]] = lst_value[i]
return dict_re


def dict_to_object(value_dict,obj_name):
filename = "%s.py"%(obj_name)
class_content = """
class {object_name}:
""".format(object_name = obj_name)
file_content = """
def __init__(self,{0}):
{1}
"""
func_content = """
@property
def {func_name}(self):
return self._{func_arg}
@{func_name}.setter
def {func_name}(self,value):
self._{func_arg} = value
"""
repr_content = """
def __repr__(self):
return "{0}".format(
{1})
"""
with open(filename,"w") as fw:
fw.write(class_content)
str_content = ""
format_str = ""
str_msg = ""
str_new_msg = ""
str_m = """
self._{0} = {1}
"""
for k, v in dict_value.items():
str_msg = str_msg + "%s = ‘‘, " % k
str_new_msg = str_new_msg + str_m.format(k, k)
fw.write(file_content.format(str_msg.strip(", "),str_new_msg))

for key in value_dict.keys():
fw.write(func_content.format(func_name = key,func_arg= key))
str_content = str_content+"{%s};"%(key)
format_str = format_str + "%s = self.%s,\n\t\t\t\t"%(key,key)
fw.write(repr_content.format(str_content,format_str))




tran_code,dict_value = read_msg("T1014530")
print dict_value
dict_to_object(dict_value,"T%s"%tran_code)

python有序的字典