Python Forum
Can I replace IF statements with a key lookup ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Can I replace IF statements with a key lookup ? (/thread-32788.html)



Can I replace IF statements with a key lookup ? - jehoshua - Mar-05-2021

If I have code like the following ( from https://python-forum.io/Thread-Convert-email-addresses-to-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 ??


RE: Can I replace IF statements with a key lookup ? - Gribouillis - Mar-05-2021

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')



RE: Can I replace IF statements with a key lookup ? - jehoshua - Mar-05-2021

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


RE: Can I replace IF statements with a key lookup ? - jehoshua - Mar-05-2021

and using it as a function works perfectly also, thanks a lot @Gribouillis