简体   繁体   English

通过在有序字典中拆分字符串来创建字典

[英]create a dict by spliting a string in an ordered dict

I have an ordered dict that represent field definition ie Name, type, width, precision 我有一个有序的字典,代表字段定义,即名称,类型,宽度,精度

it looks like this: 它看起来像这样:

 OrderedDict([(u'CODE_MUN', 'str:8'), (u'CODE_DR_AN', 'str:8'),
 (u'AREA', 'float:31.2'), (u'PERIMETER', 'float:31.4')])

I would like to create a dict for each item that would be like this: 我想为每个项目创建一个像这样的字典:

{'name' : 'CODE_MUN', 'type': 'str', 'width': 8, 'precision':0} for fields without precision {'name' : 'CODE_MUN', 'type': 'str', 'width': 8, 'precision':0}用于没有精度的字段

and

{'name' : 'AREA', 'type': 'float', 'width': 31, 'precision':2 } for fiels with precision {'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]

of course I have index error when there is no precision defined. 当没有定义精度时,我当然会有索引错误。 What would be the best way to achieve that? 实现这一目标的最佳方法是什么?

You have to check precision is there or not. 您必须检查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

This might be help 这可能有帮助

Use a try-except block. 使用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

You could also test for length using an if-else block. 您也可以使用if-else块测试长度。 The methods are pretty close and I doubt this is a situation where it really matters, but for more on asking forgiveness vs permission you can see this question . 这些方法非常接近,我怀疑这是否真的很重要,但是要了解更多关于宽恕允许的信息 ,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM