Reputation: 302
Is there any way to use dict comprehension inside a fstring? THe case is the following:
a = ['a', 'b', 'c', 'd']
list_comprehension = [v for v in a]
my_f_string = f"dict comprehension {v:None for v in a}"
I do not wanna use format interpolation ("{}".format(dict_comprehension)
). I want to use the most pythonic way to include that list comprehension inside the fstring to be used for logging data.
Upvotes: 3
Views: 2038
Reputation: 106102
What you are trying to do can be simply done as
dict_comp = {v:None for v in a}
my_f_string = f"dict comprehension {dict_comp}"
Or if you really want to use a dict comprehension inside an f-string then you have to place {v:None for v in a}
inside another curly braces with a space before and after {v:None for v in a}
.
my_f_string = f"dict comprehension { {v:None for v in a} }"
Upvotes: 1
Reputation: 24107
Yes, of course there is. You simply need to wrap the comprehension in parenthesis ( )
, since two consecutive {
s are interpreted as a literal "{"
string.
a = ['a', 'b', 'c', 'd']
list_comprehension = [v for v in a]
This works:
my_f_string = f"dict comprehension {({v:None for v in a})}"
print(my_f_string)
Output:
dict comprehension {'a': None, 'b': None, 'c': None, 'd': None}
But, this does not work (Stack Overflow's syntax highlighting also helpfully shows that):
my_f_string = f"dict comprehension {{v:None for v in a}}"
print(my_f_string)
Output:
dict comprehension {v:None for v in a}
Upvotes: 4
Reputation: 71610
In this case I prefer dict.fromkeys
:
my_f_string = f"dict comprehension {dict.fromkeys(a)}"
Shorter and much more elegant :)
And now:
print(my_f_string)
Output:
dict comprehension {'a': None, 'b': None, 'c': None, 'd': None}
Upvotes: 1