Cmarv Cmarv - 3 months ago 9
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(m.group(0).upper()), value, flags=re.IGNORECASE)


but
re_value
is blank.

Can anyone explain why is that.

Thx.

[update]

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

Answer

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(
    pattern_interfaces,
    lambda m: interfaces['A'][m.group(0).upper()],
    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.

Comments