简体   繁体   中英

create dictionary conditionally with Python

There are 4 possible values for a variable 'OAS'.

'N/A' 
[2344.099] # numeric with dot
[222] # numeric without dot
'Some Exception'

Based on the value, I need to create the dictionary. Format of dictionary look like this.

oas = {
    'greeksName':'',
    'status': '',
    'exception': ''
    'value': ''
}

my current logic looks very ugly.

if OAS == 'N/A':
    oas = {
        'greeksName': 'OAS',
        'status': 'Not Applicable',
        'exception': 'Not Applicable'
        'value': None
    }
elif is_a_valid_value(OAS):
    oas = {
        'greeksName': 'OAS',
        'status': 'success',
        'exception': ''
        'value': OAS
    }
else:
    oas = {
        'greeksName': 'OAS',
        'status': 'fail',
        'exception': OAS
        'value': None
    }   

Can suggest some clean and Pythonic way?

Here lies my small suggestion to improve the style and optimization.

# change the variable name 'oas' to something more readable if possible
oas = {
        'greeksName': 'OAS',
        'status': 'Not Applicable',
        'exception': 'Not Applicable'
        'value': None
    } 

if is_a_valid_value(OAS):
    oas['status'] = 'success'
    oas['exception'] = None  # changed from ''
    oas['value'] = OAS

elif not OSA == 'N/A':
    oas['status'] = 'fail'
    oas['exception'] = OAS
     

You could do something like this, but as to whether or not it's preferable is in the eye of the beholder:

if OAS == 'N/A':
   status = 'Not Applicable'
   exception = 'Not Applicable'
   value = None
elif is_a_valid_value(OAS):
   status = 'success'
   exception = ''
   value = OAS
else:
   status = 'fail'
   exception = OAS
   value = None

oas = {
    'greeksName': 'OAS',
    'status': status,
    'exception': exception,
    'value': value,
}

(I might add I'm not a big fan of variables with names that differ only by case, as in OAS and oas )

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