2.4 딕셔너리 #Writing Idiomatic Python 3.1

oen·2022년 3월 4일
0

1. switch...case 문 대신(if...else 문 대신) dict 사용

👎

def apply_operation(left_operand, right_operand, operator):
    import operator as op
    if operator == '+':
        return op.add(left_operand, right_operand)
    elif operator == '-':
        return op.sub(left_operand, right_operand)
    elif operator == '*':
        return op.mul(left_operand, right_operand)
    elif operator == '/':
        return op.truediv(left_operand, right_operand)


print(apply_operation(1, 2, '+'))
3

👍

def apply_operation(left_operand, right_operand, operator):
    import operator as op
    operator_mapper = {
        '+': op.add,
        '-': op.sub,
        '*': op.mul,
        '/': op.truediv,
    }

    return operator_mapper[operator](left_operand, right_operand)


print(apply_operation(1, 2, '+'))
3

2. dict.get에 디폴트 값 제공

👎

configuration = {}

if 'severity' in configuration:
    print(configuration['severity'])
else:
    print('Info')
Info

👍

configuration = {}

print(configuration.get('severity', 'Info'))
Info

if 문을 사용할 필요가 없이 코드가 명확해진다

3. dict comprehension 사용

👎

user_list = [
    {'id': 0, 'email': 'a@com'},
    {'id': 1},
]

user_email = {}
for user in user_list:
    if user.get('email'):
        user_email[user['id']] = user['email']

print(user_email)
{0: 'a@com'}

👍

user_list = [
    {'id': 0, 'email': 'a@com'},
    {'id': 1},
]

user_email = {
    user['id']: user['email']
    for user in user_list if user.get('email')
}

print(user_email)
{0: 'a@com'}
profile
🐾

0개의 댓글