[Python] Increment a variable inside a comprehension

Discussão em 'Python' iniciado por Stack, Novembro 23, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to increment a variable in a dictionary comprehension?

    For a very basic example:

    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    x = 1
    alpha_numbers = {char: x for char in alphabet}


    I would like x to be x += 1 for each char in the alphabet container (a:1, b:2, c:3, etc). But every way I try to increment it inside the dictionary comprehension is invalid syntax.

    I know the general pattern is:

    {key: value for key in container}


    But I can't figure out how to increment the value for each key in the container.

    Is it possible to do it? Or is there a better way?

    Continue reading...

Compartilhe esta Página