ajknzhol
ajknzhol

Reputation: 6460

Search and replace characters in string from the list

I have two dict's like this,

in_dict = {
    '1': 'active_rate',
    '2': 'purchase_per_active'
}

formula = {
    'total_purchase': 'B1*B2'
}

I need to find the integers in the value of formula dict 'B1*B2' and then get the value for integer corresponding to the integers from the in_dict dictionary and finally replace B1 with active_rate and B2 with purchase_per_active.

So, final formula dict should be like

formula = {
    'total_purchase': 'active_rate*purchase_per_active'
}

The code so far

for key, value in formula.items():
    numbers = re.findall("\d+", value)               # ['1','2']
    values = [in_dict.get(num) for num in numbers]   # ['active_rate', 'purchase_per_active']

Now, how to replace the 'B1' with 'active_rate' and 'B2' with 'purchase_per_active'?

The example shown here is just for sample. The code nature should be generic.

Upvotes: 3

Views: 77

Answers (1)

Martin Evans
Martin Evans

Reputation: 46779

You could use a regular expression substitution using a function to directly lookup each of the parameters:

import re

in_dict = {
    '1': 'active_rate',
    '2': 'purchase_per_active'
}

formula = {
    'total_purchase': 'B1*B2'
}

def lookup(number):
    return in_dict[number.group(1)]

for key, value in formula.items():
    formula[key] = re.sub("[a-zA-Z](\d+)", lookup, value)

print formula

This gives the following output:

{'total_purchase': 'active_rate*purchase_per_active'}

To me it might make more sense if in_dict stored keys such as 'B1', 'C1'.

import re

in_dict = {
    'A1': 'active_rate1',
    'A2': 'purchase_per_active1',
    'B1': 'active_rate2',
    'B2': 'purchase_per_active2'
}

formula = {
    'total_purchase': 'B1*B2',
    'total_purchase2': 'A1*A2'
}

def lookup(cell):
    return in_dict[cell.group(1)]

for key, value in formula.items():
    formula[key] = re.sub("([a-zA-Z]\d+)", lookup, value)

print formula

{'total_purchase2': 'active_rate1*purchase_per_active1', 'total_purchase': 'active_rate2*purchase_per_active2'}

Upvotes: 3

Related Questions