I have a dictionary whose values may contain keys that are already in the dictionary. What we are actually talking about are parameters. Sometimes a parameter is defined by a number plus another parameter, etc.
It looks something like this:
paramDict = {'ad': '2*dmcg/factor*(xw/factor)',
'dmcg': 2.05e-07,
'dxwn_3vna': 10.0,
'factor': 1,
'xw': '0+dxwn_3vna'}
If there is another parameter in the value it is of type string, otherwise it is an int
or a float
. After the replacing I want the value to be a float.
The code I wrote to solve this problem is this:
for _ in range(10):
for key, value in paramDict.items():
if type(value) is str:
matchList = re.findall('[a-z]\w*', value)
matchList = [match for match in matchList if match != 'e']
for match in matchList:
param = paramDict[match]
paramDict[key] = value.replace(match, str(param))
try:
paramDict[key] = eval(paramDict[key])
except:
pass
It works as far as I can tell, but it just doesn't feel right to just repeat the whole process a finite number of times and hope that all the strings have been replaced. Is there a safer way?