Reputation: 167
I have a dict comprehension that looks like this:
bar = {
n: n**2
for n in range(1, 10)
}
Is there any way to add an additional key to the dict in the same expression? I was thinking of something like this:
bar = {
'foo': 'bar',
n: n**2
for n in range(1, 10)
}
This doesn't work though. How can I achieve this? For now I am adding the additional entry manually afterwards but it would be good if I could do it in the same expression.
I know that the use case is not very clear from my example but in my actual code it would make things a lot easier.
Upvotes: 3
Views: 701
Reputation: 306
In python 3.9.0+, the |
operator merges two dictionaries
bar = { 'foo': 'bar' } | {
n: n**2
for n in range(1, 10)
}
Upvotes: 6
Reputation: 6826
Do it in two operations, e.g.:
bar = {
'foo': 'bar'
}
bar.update(
{
n: n**2
for n in range(1, 10)
}
)
print( f"{bar=}" )
result:
bar={'foo': 'bar', 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
Upvotes: 1