B
B
beduin012018-07-03 15:07:58
Python
beduin01, 2018-07-03 15:07:58

How to simplify code that replaces values ​​in a dictionary?

How can the following code be simplified?

if r['opcode'] == 1:
    r['opcode'] = str(r['opcode']).replace('1', 'Оплата')
if r['opcode'] == 2:
    r['opcode'] = str(r['opcode']).replace('2', 'Возврат')
if r['opcode'] == 3:
    r['opcode'] = str(r['opcode']).replace('3', 'Рекуррентное списание')
if r['opcode'] == 4:
    r['opcode'] = str(r['opcode']).replace('4', 'Блокировка')

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilyas, 2018-07-03
@id2669099

d = {
    1: 'Оплата',
    2: 'Возврат',
    3: 'Рекуррентное списание',
    4: 'Блокировка',
}

r['opcode'] = d[r['opcode']]

R
Ruslan., 2018-07-03
@LaRN

To change the value in the dictionary, you can simply:
if r['opcode'] == 1:
r['opcode'] = 'Payment'

S
Stanislav Pugachev, 2018-07-03
@Stqs

r['opcode'] = ['Оплата', 'Возврат', 'Рекуррентное списание', 'Блокировка'][r['opcode'] - 1]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question