I have a string templ with variable part that I have to convert with local variables. Variable part of string have a dictionary cur_cols_dct from which I want to get a single value. Key of a dictionary is also a variable: col
templ = "COMMENT IS '{cur_cols_dct[col]}'" # string with variable part
cur_cols_dct = {'art_id':'ID of article'} # dictionary
col = 'art_id' # variable for dictionary key
I have to get string with a single value from a dictionary:
COMMENT IS 'ID of article'
I can use f-string for this goal and it works:
print (f"COMMENT IS '{cur_cols_dct[col]}'")
But when I try to use format(locals()) it doesn't work, because Python can't recognize that 'col' is not a literal but a variable:
print(templ.format(**locals()))
I get an error: KeyError: 'col'
But I can't use f-string in this case because I define templ before I get cur_cols_dct and col variables.
Is there any way to get value from dictionary when both dictionary and key value are variables by using format(**locals())? Or what can I use instead of format?
**locals()doesn't include global variables.templbeforecur_cols_dct? Why not do it afterwards with anf-stringjust as you said?format()just does simple variable replacement, it doesn't evaluate expressions like f-strings do.cur_cols_dct[col]is an expression.templ = "COMMENT IS '{}'"and later do directlytempl.format(cur_cols_dct[col])ortempl.format(any_other_value)without usinglocals(). You can even use it in loop -for value in some_data: print(templ.format(valuie))- but if you want to do something more complex then maybe use templatesjinja