1

This might seem like a wierd requirement, but I am looking for a good implementation to do this.

I have a dict like

vals = dict(red='#F00', green='#0F0', blue='#00F')

and a string like

tpl = '{red}:{green}:{blue}'

and the str.formatted output

output = tpl.format(**vals)

All is well till here. However, I now need to do the reverse of this. I have to turn a string like '#F00:#0F0:#00F' into a dict of the values that we previously started with. Of course, I could just split and strip the string and take the values I need, but it will fail in the event the tpl string should change.

Any good ideas on how I can do this (If it can even be done, that is)?

1 Answer 1

2

You can use regular expressions. (And maybe then you'll have two problems.)

>>> import re
>>> pattern = re.compile('(#[\da-fA-F]{3})')
>>> l = pattern.findall(output)
['#F00', '#0F0', '#00F']
>>> dict(zip(('red', 'green', 'blue'), l))
{'blue': '#00F', 'green': '#0F0', 'red': '#F00'}
>>>
Sign up to request clarification or add additional context in comments.

5 Comments

+1 Nice and simple, me likes it :). Also, we do have two problems, the second being we now need a regex that matches the substitution strings correctly ;)
You want something like parse('{red}:{green}:{blue}', '#F00:#0F0:#00F') that returns vals? That's more complicated, why don't you write out a solution and post it here, and it can be improved/fixed if required.
@rm, have been working on it for over a couple hours now. So far, its little more than doctests and a long undo history :)
But I am starting to doubt the possibility of such a thing now.
Yep, this is the best way we have :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.