AlliDeacon AlliDeacon - 1 month ago 6
Python Question

Use a xref of values to sub into tuple based on value - Python

I have a list of xref values

internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}


that I would like to use to sub a value in a tuple:

('03', 'S/N A1631703')


So my resulting tuple would be

('33', 'S/N A1631703')


Can someone point me in the direction of the tools I could use to accomplish this?

Answer

Unpack and access the dict using the first element, presuming you have an list of tuples:

internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}

lst = [('03', 'S/N A1631703'),('05', 'S/N A1631703')]

lst[:] = ((internal_customer[a], b) for a,b in t)    
print(t)

tuples are immutable so there is no notion of mutating, you have to create a new tuple comprising of the new value from the dict and the existing second element. The lst[:] syntax at least allows you to modify the original list. You can of course just reassign the name or create a completely new list if you want to maintain the original.