This is about this answer: https://stackoverflow.com/a/58327293/1092820
It was originally a very distinct answer:
You could subclass Formatter and then it is fairly easy:
import string class PartialFormatter(string.Formatter): def __init__(self, missing='~~', bad_fmt='!!'): self.missing, self.bad_fmt=missing, bad_fmt def get_field(self, field_name, args, kwargs): # Handle a key not found try: val=super(PartialFormatter, self).get_field(field_name, args, kwargs) # Python 3, 'super().get_field(field_name, args, kwargs)' works except (KeyError, AttributeError): val=None,field_name return val def format_field(self, value, spec): # handle an invalid format if value==None: return self.missing try: return super(PartialFormatter, self).format_field(value, spec) except ValueError: if self.bad_fmt is not None: return self.bad_fmt else: raise d1={'A':'x', 'B':'y', 'C':'{A}_foo', 'D':'bar_{B}'} d2={} fmt=PartialFormatter() for k,v in d1.items(): if '{' in v: d2[k]=fmt.format(v,**d1) else: d2[k]=v >>> d2 {'A': 'x', 'B': 'y', 'C': 'x_foo', 'D': 'bar_y'}
Then I posted my own answer a minute later:
With a list comprehension on
d.items
, we can applyval.format(**d)
on each value to interpolate the values with the dict itself:>>> d = {'A':'x', 'B':'y', 'C':'{A}_foo', 'D':'bar_{B}'} >>> o = dict([ (key, val.format(**d)) for key,val in d.items() ]) >>> print (o) {'A': 'x', 'B': 'y', 'C': 'x_foo', 'D': 'bar_y'}
Then 7 minutes afterwards, the author of the first answer edited their answer to substantially change it into a near exact, but unintentional, duplicate of my answer:
Just use Python string formatting and expand the
d1
dict as the arguments:d1={'A':'x', 'B':'y', 'C':'{A}_foo', 'D':'bar_{B}'} d2={k:v.format(v,**d1) for k,v in d1.items()} >>> d2 {'A': 'x', 'B': 'y', 'C': 'x_foo', 'D': 'bar_y'}
Since the author actually decreased the level of contribution their answer made (from being a distinct answer to being noise), is the correct course of action here to roll back the edit?
I do think it was unintentional so I don't know if flagging is the right answer here.