python - Doing a format string substitution within a dictionary -
i trying figure out if there way kind of 'soft code' values in dictionary, , able substitute fixed string values places later on. in other words, how can, strings, like:
environment = """{'sdc_period':'%(period)s','family':'%(legup_family)s','device_family':'"%(fpga_family)s"','device':'%(fpga_device)s'}""" % self
and substitute given desired values environment
string object self
instance namespace dictionary, able straight substitution dictionary itself, perhaps below?
environment = {'sdc_period':'%(period)s','family':'%(legup_family)s','device_family':'"%(fpga_family)s"','device':'%(fpga_device)s'} % self
however, know not allowed %
operand not supported dictionary object types, above line not work, i'm using express objective able create dictionary substituting string objects 'soft coded' values.
right now, not know of way able substitute in strings dictionary values, have no selection following:
import ast environment = """{'sdc_period':'%(period)s','family':'%(legup_family)s','device_family':'"%(fpga_family)s"','device':'%(fpga_device)s'}""" % self env_dict = ast.literal_eval(environment)
in order able dictionary object desired key:value pairs.
however, seems much simple getting dictionary object right key-values. appreciate if has other suggestions me.
thank you!
if want complex interpolation on strings comprising dict
values (or string, matter), can utilize format
.
>>> period_val = "1970" >>> family_val = "smith" >>> environment = {'sdc_period': '{period}s'.format(period = period_val), 'family': '{legup_family}s'.format(legup_family = family_val)} >>> print environment {'sdc_period': '1970s', 'family': 'smiths'}
for simpler strings above, utilize number references instead (i.e. {0}
, since it's less typing), , no interpolation situations, assign values straight using variable, more complicated interpolation, if interpolating 3 or 4 variables 1 string, referencing things name can help code become clearer.
here's more info on format.
python string dictionary
No comments:
Post a Comment