[英]create a dict by spliting a string in an ordered dict
我有一个有序的字典,代表字段定义,即名称,类型,宽度,精度
它看起来像这样:
OrderedDict([(u'CODE_MUN', 'str:8'), (u'CODE_DR_AN', 'str:8'),
(u'AREA', 'float:31.2'), (u'PERIMETER', 'float:31.4')])
我想为每个项目创建一个像这样的字典:
{'name' : 'CODE_MUN', 'type': 'str', 'width': 8, 'precision':0}
用于没有精度的字段
和
{'name' : 'AREA', 'type': 'float', 'width': 31, 'precision':2 }
用于精确的字段
for keys, values in fieldsDict.iteritems():
dict = {}
dict['name'] = keys
props = re.split(':.', values)
dict['type'] = props[0]
dict['width'] = props[1]
dict['precision'] = props[2]
当没有定义精度时,我当然会有索引错误。 实现这一目标的最佳方法是什么?
您必须检查precision
是否存在。
from collections import OrderedDict
import re
fieldsDict = OrderedDict([(u'CODE_MUN', 'str:8'), (u'CODE_DR_AN', 'str:8'),
(u'AREA', 'float:31.2'), (u'PERIMETER', 'float:31.4')])
for keys, values in fieldsDict.iteritems():
dict = {}
dict['name'] = keys
props = re.split(':.', values)
dict['type'] = props[0]
dict['width'] = props[1]
if len(props) == 3:
dict['precision'] = props[2]
else:
dict['precision'] = 0
print dict
这可能有帮助
使用try-except块。
for keys, values in fieldsDict.iteritems():
dict = {}
dict['name'] = keys
props = re.split(':.', values)
dict['type'] = props[0]
dict['width'] = props[1]
try:
dict['precision'] = props[2]
except IndexError:
dict['precision'] = 0
您也可以使用if-else块测试长度。 这些方法非常接近,我怀疑这是否真的很重要,但是要了解更多关于宽恕与允许的信息 ,请参见此问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.