0

How to do a dictionary literal within the f-string curly braces?

d_all = {d:d+2 for d in range(10)}
keys = [2,5]
tmp_dict = {d:d_all[d] for d in keys}
print(f'values: {tmp_dict}')

print(f'keys: {[d for d in keys]}')  # list works
print(f'dict: { {{d:d_all[d] for d in keys}} }'  # ???
fivelements
  • 1,487
  • 2
  • 19
  • 32
  • 3
    Simple answer: you don't. Don't try to cram stuff into f-strings, just define the variable beforehand then put it in the f-string. Or, use `.format`. – Aplet123 Dec 29 '20 at 16:11
  • 5
    Does this answer your question? [Dictionary/set comprehensions inside of f-string](https://stackoverflow.com/questions/49120113/dictionary-set-comprehensions-inside-of-f-string) – Random Davis Dec 29 '20 at 16:13
  • you do it the same way, but have are missing one `)` and have a pair of `{` too much – Alexander Riedel Dec 29 '20 at 16:14
  • 1
    You just need to surround the dictionary comprehension with another pair of braces with spaces between the inner and outer opening and closing ones and it will work. Also, did you mean to use `all_dict` instead of `d_all`? – Amal K Dec 29 '20 at 16:24
  • That isn't a dictionary literal. That's a dictionary comprehension. And it works just fine, you just have an extra pair of parentheses. – juanpa.arrivillaga Dec 29 '20 at 16:32
  • space and one pair curly braces works! – fivelements Dec 29 '20 at 16:40

1 Answers1

3

Try this:

print(f'dict: { {d:d_all[d] for d in keys} }')
AWhiteFox
  • 96
  • 5
  • 1
    just realize the auto format feature in PyCharm will remove the space between the 2 curly braces, and without the space, it will not work. – fivelements Dec 29 '20 at 18:24