Search code examples
pythonpython-3.xdictionary-comprehension

Dict comprehension with additional key


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.


Solution

  • In python 3.9.0+, the | operator merges two dictionaries

    bar = { 'foo': 'bar' } | {
        n: n**2
        for n in range(1, 10)
    }