Cmarv Cmarv - 10 months ago 51
Python Question

re.sub not matching nested dictionary

with the following dict:

interfaces = {'A':{'568':'A1','590':'A2'},'B':{'590':'B2'}}

i what to replace the value='590' with A2 while setting the A element and B2 while setting the B element.

I've tried :

pattern_interfaces = r'\b({})\b'.format('|'.join(sorted(re.escape(k) for k in interfaces['A']))) #=>(568|590)

re_value = re.sub(pattern_interfaces, lambda m: interfaces.get(, value, flags=re.IGNORECASE)

is blank.

Can anyone explain why is that.



ok , i see where i was wrong lambda m: interfaces['A'] does what i needed.


You matched keys from interfaces['A'], not from interfaces. Use that nested dictionary if you are going to generate a regex from that keys :

re_value = re.sub(
    lambda m: interfaces['A'][],
    value, flags=re.IGNORECASE)

I replaced the dict.get() call with direct subscription; you can only match existing keys with your regex, no need to account for missing keys here.

Your sample also matched numbers, not letters, so neither the .upper() call nor the re.IGNORECASE will make a difference here.