简体   繁体   中英

Python dictonary with string placeholders and defaults

I have the following problem in python2.7. I want to have a template dictionary like this:

my_dict = {
    'key_1' : %(key_1)s,
    'key_2' : %(key_2)s,
}

and I want to use it like this:

new_dict = my_dict % {'key_1': 'something', 'key_2': 'anything'}

but this is raising an exception:

TypeError: unsupported operand type(s) for %: 'dict' and 'dict'

My question has two points here:

  1. Is there any way or structure, preferably dictionary, to achieve this:
  2. Considering there is, is there a way to default the values if no value is passed ?

What I mean with 2 is:

my_dict = {
    'key_1' : %s or None, # if no value is interpolated at key 'key_1'
}
template = {
    'key_1' : '%(key_1)s',
    'key_2' : '%(key_2)s',
}

values_dict = {'key_1': 'something', 'key_2': 'anything'}

Then to make a new dict with all the formatting:

new_dict = dict((key, template[key] % values_dict) for key, value in template.items())

Or if you're ok updating the original dict :

for key, value in template.items():
    template[key] %= values_dict

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM