teepee
teepee

Reputation: 2714

How can you put dict and get method inside an f-string?

I have this dictionary that I want to embed inside an f-string to shorten up my code (for golfing purposes). Is there any way to include the braces inside the f-string braces?

# 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'

I can't swap out the {}.get notation for the dict().get because my keys are numbers (unless there's a hack to adjust that but it probably will end up being more characters than I have already).

Thanks in advance.

Upvotes: 0

Views: 297

Answers (1)

Random Davis
Random Davis

Reputation: 6857

One, you have to use different quote types on your string, otherwise the quotes inside the dict literal will mess things up. Secondly, you just have to add a space around the dictionary literal and the .get():

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

Source for adding the spaces: this answer.

Upvotes: 2

Related Questions