Question

I would like to do something like the following, I don't know if it's possible:

d={
'error': ' Please insert a valid (%s) name'
'required': ' Please insert your (%s) name'
}

d1 = d % 'first'
d2 = d % 'last'

So basically I want something like a dictionary template. Is it a way to make this possible? It would be more elegant to do so and as well respect the DRY principle.

Expected result:

d1 == {'required': ' Please insert your (first) name',
       'error': ' Please insert a valid (first) name'}

d2 == {'required': ' Please insert your (last) name',
       'error': ' Please insert a valid (last) name'}
Was it helpful?

Solution

How about define a function that generate a dictionary?

>>> def make_msg_dict(part):
...     return {
...         'error': ' Please insert a valid (%s) name' % part,
...         'required': ' Please insert your (%s) name' % part,
...     }
...
>>> d1 = make_msg_dict('first')
>>> d2 = make_msg_dict('last')
>>> d1
{'required': ' Please insert your (first) name',
 'error': ' Please insert a valid (first) name'}
>>> d2
{'required': ' Please insert your (last) name',
 'error': ' Please insert a valid (last) name'}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top