[Python] Convert dictionary entries into variables [duplicate]

Discussão em 'Python' iniciado por Stack, Julho 12, 2025.

  1. Stack

    Stack Membro Participativo

    Is there a Pythonic way to assign the values of a dictionary to its keys, in order to convert the dictionary entries into variables? I tried this out:

    >>> d = {'a':1, 'b':2}
    >>> for key,val in d.items():
    exec('exec(key)=val')

    exec(key)=val
    ^
    SyntaxError: invalid syntax


    I am certain that the key-value pairs are correct because they were previously defined as variables by me before. I then stored these variables in a dictionary (as key-value pairs) and would like to reuse them in a different function. I could just define them all over again in the new function, but because I may have a dictionary with about 20 entries, I thought there may be a more efficient way of doing this.

    Continue reading...

Compartilhe esta Página