Python Forum

Full Version: Can I replace IF statements with a key lookup ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
If I have code like the following ( from https://python-forum.io/Thread-Convert-e...VCF-format ):

    name = ""
    if 'cn' in record:
        name = record['cn'][0]
    
    surname = ""
    if 'sn' in record:
        surname = record['sn'][0]
    
    given_name = ""
    if 'givenName' in record:
        given_name = record['givenName'][0]
    
    display_name = ""
    if 'displayName' in record:
        display_name = record['displayName'][0]
    
    email = ""
    if 'mail' in record:
        email = record['mail'][0]
and the input data is from an LDIF formatted file, and the record is coming from a dictionary/class as such

Quote:OrderedDict([('objectClass', ['inetOrgPerson']), ('cn', ['Forrest Gump']), ('sn', ['Gump']), ('displayName', ['Forrest Gump']), ('mail', ['[email protected]'])])

can I use some sort of key lookup as explained at Python: How Key lookup works in Dictionary and how to customize it? ??

simply to replace all the ugly IF statements with a simple key lookup ??
You could try
name = record.get('cn', ('',))[0]
Or better, make a function
def extract(record, key, default=''):
    return record.get(key, (default,))[0]

name = extract(record, 'cn')
surname = extract(record, 'sn')
(Mar-05-2021, 10:15 PM)Gribouillis Wrote: [ -> ]You could try
name = record.get('cn', ('',))[0]
Or better, make a function
def extract(record, key, default=''):
    return record.get(key, (default,))[0]

name = extract(record, 'cn')
surname = extract(record, 'sn')

Thanks, that's awesome, I just tried the first piece of code and it works just fine. Will try the other part now as a function.
and using it as a function works perfectly also, thanks a lot @Gribouillis