简体   繁体   中英

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

and

{'name' : 'AREA', 'type': 'float', 'width': 31, 'precision':2 } for fiels with precision

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.

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.

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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