Title: Python String format with dynamic key throws KeyError
Tags: python;python-3.7
Question: import re
regex = r"\{(.*?)\}"
v = '2020-01-21'
x = "xdate({date1}, 'mm/dd/yyyy')"
yy = x.format(date1=v)
print(yy)
#works as expected
m1 = re.search(regex, x)
if m1:
p1 = m1.group(0)
#p1 = m1.group(1)
print(p1)
p = x.format(p1=v)
print(p)
In the above program, I can get it to work when I print yy but I do not want to hard code the string literal date1, I am trying to read the string literal and use it in format()
I am receiving KeyError: 'date1'. Any suggestions please?

Here is the accepted answer: You can use positional placeholder {} instead of named ones.
So instead of:
x = "xdate({date1}, 'mm/dd/yyyy', {date2}, 'dd/mm/yyyy', {date3}, 'yyyy/mm/dd')"
yy = x.format(date1=v1, date2=v2, date3=v3)
x = "xdate({}, 'mm/dd/yyyy', {}, 'dd/mm/yyyy', {}, 'yyyy/mm/dd')"
yy = x.format(v1, v2, v3)
Comment for this answer: You can use multiple `{}`s in the format string. I've updated the answer accordingly then.
Comment for this answer: It's actually the same thing. Use multiple `{}`s in the format string. I've updated my answer accordingly.
Comment for this answer: Thank you, how does it work if we have more than one positional arg?
Comment for this answer: Thanks again. I mean if we have ```xdate({date1}, 'mm/dd/yyyy', {date2}, 'dd/mm/yyyy', {date3}, 'yyyy/mm/dd')``` and if we use ```{}``` in place of date1, date2 and date3, how do we substitute with different values? sorry if you have already covered this in your answer but it was not clear to me.

Here is another answer: Since you are already using Python 3.7, why not use f-strings to format the strings. It's arguably more readable and slightly faster too.
import re
regex = r"\{(.*?)\}"
v = "2020-01-21"
date1 = v
x = f"xdate({date1}, 'mm/dd/yyyy')"
yy = x
print(yy)
m1 = re.search(regex, x)
if m1:
p1 = m1.group(0)
# p1 = m1.group(1)
print(p1)
p = x.format(p1=v)
print(p)
This prints,
&gt;&gt; xdate(2020-01-21, 'mm/dd/yyyy')

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2020:00:02/10/20', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><python-3.7>', 'Title': 'Python String format with dynamic key throws KeyError', 'ViewCount': 217, 'id': 60157269, 'user_AboutMe': None, 'user_AccountId': 13546444.0, 'user_DisplayName': 'dcu', 'user_Reputation': 197.0, 'user_Views': 41.0, 'user_id': 9772608.0}}