python字典是有序的吗_python有序的字典

python中有序的字典 OrderedDict

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @Time : 2017/10/13 09:45

# @Author : wlgo2108

# @Site :

# @File : readmsg.py

# @Software: PyCharm

# @Email : wlgo2108@126.com

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)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值