Python 如何将dict和get方法放入f字符串中?

Python 如何将dict和get方法放入f字符串中?,python,python-3.x,string,dictionary,f-string,Python,Python 3.x,String,Dictionary,F String,我有这个字典,我想嵌入到一个f字串中,以缩短我的代码(用于打高尔夫球)。有没有办法将大括号包含在f字串大括号中 # what I have: i=2 a={1:'a',2:'b',3:'c'}.get(i,'g') b=f'{a} is the letter' # what I want to do but get a syntax error: b=f'{{1:'a',2:'b',3:'c'}.get(i,'g')} is the letter' # desired output: 'b

我有这个字典,我想嵌入到一个f字串中,以缩短我的代码(用于打高尔夫球)。有没有办法将大括号包含在f字串大括号中

# what I have:
i=2
a={1:'a',2:'b',3:'c'}.get(i,'g')
b=f'{a} is the letter'

# what I want to do but get a syntax error:
b=f'{{1:'a',2:'b',3:'c'}.get(i,'g')} is the letter'

# desired output:
'b is the letter'
我不能为
dict().get
换掉
{}.get
符号,因为我的键是数字(除非有人对此进行调整,但它可能会比我已经拥有的字符更多)


提前感谢。

首先,您必须在字符串上使用不同的引号类型,否则dict文本中的引号会把事情搞砸。其次,您只需在字典文本和
.get()
周围添加一个空格:


添加空格的来源:。

你想让输出看起来像什么?我刚刚澄清了@Greg
f{dict([(1,'a'),(2,'b'),(3,'c')])。get(I,'g')}是字母“
你为什么要添加额外的空格?@martineau很好的问题,如果我能解释的话,我会的。事实上,我认为你添加链接的答案中的问题解释了它:“…双括号导致输出中的文字括号…”,也就是说,f字符串是如何解析的。
b=f"{ {1:'a',2:'b',3:'c'}.get(i,'g') } is the letter"