sopana
sopana

Reputation: 375

python - Replace values of keys with values corresponding to different keys in the same dictionary

I have no experience in Python scripting, but as a requirement in my project I had to build a code and here's the problem I'm experiencing -

I have a dictionary with below values which comes from a unix script to set common paths which I've to read in python -

{'# blah blah blah ': '', 'START_DIR': '/PATH/TO/StartDir', 'FIRST_DIR': '${START_DIR}/FirstDir', '# GIBBERISH': 'MORE GIBBERISH', 'SECOND_DIR': '${FIRST_DIR}/SecondDir'....so on and so forth}

I was able to read the values but the values would be like -

FIRST_DIR="${START_DIR}/FirstDir"
SECOND_DIR="${FIRST_DIR}/SecondDir"
.....

As the unix variables don't expand while being read in Python and I want replace the values in the dictionary for all the ${} enclosed variables in values of dict like below -

{'# blah blah blah ': '', 'START_DIR': '/PATH/TO/StartDir', 'FIRST_DIR': '/PATH/TO/StartDir/FirstDir', '# GIBBERISH': 'MORE GIBBERISH', 'SECOND_DIR': '/PATH/TO/StartDir/FirstDir/SecondDir'....so on and so forth}

I've searched this forum and the closest answer I got is found at this link - https://codereview.stackexchange.com/questions/80273/replace-keys-in-values-with-key-values-from-same-dictionary but I was not able make it work for my problem. Could anyone of you please help me out?

Thanks for your time!

Upvotes: 2

Views: 358

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

You could use re.search to find a unix style variable. If you find a match, replace that variable with the one from your dictionary. The while loop is because these variables can refer to variables that have more variables, etc. So continue until all variables have been expanded.

import re
def convert_dict(d):
    while any(re.search('\${(.*)}', i) for i in d.values()):
        for key, value in d.items():
            match = re.search('\${(.*)}', value)
            if match:
                d[key] = value.replace(match.group(0), d[match.group(1)])

Output

>>> d = {'FIRST_DIR': '${START_DIR}/FirstDir',
         '# GIBBERISH': 'MORE GIBBERISH',
         '# blah blah blah ': '',
         'SECOND_DIR': '${FIRST_DIR}/SecondDir',
         'START_DIR': '/PATH/TO/StartDir'}
>>> convert_dict(d)
{'FIRST_DIR': '/PATH/TO/StartDir/FirstDir',
 'START_DIR': '/PATH/TO/StartDir',
 '# blah blah blah ': '',
 '# GIBBERISH': 'MORE GIBBERISH',
 'SECOND_DIR': '/PATH/TO/StartDir/FirstDir/SecondDir'}

Upvotes: 3

Related Questions