How Do You Replace Variables With Their Values?

Ben Finney ben+python at benfinney.id.au
Fri Jul 12 00:09:28 EDT 2019


Aldwin Pollefeyt <aldwinaldwindev at gmail.com> writes:

> dinner = {'Starters':['Fried Calamari', 'Potted crab'],'Main
> Course':['Fish', 'Meat'], 'Desert':['Cake', 'Banana Split']}
>
> # Don't ask where I got the dinner from
>
> for meal in dinner.keys():
>     exec(meal.replace(' ','_') + ' = list(dinner[meal])')
>
> print(Starters)
> print(Main_Course)
> print(Desert)

Why do you think this is needed? Why (there may be some reason! but you
have not told us what that is) can your program not just::

    print(dinner['Starters'])
    print(dinner['Main Course'])
    print(dinner['Desert'])

> OUTPUT:
> ['Fried Calamari', 'Potted crab']
> ['Fish', 'Meat']
> ['Cake', 'Banana Split']

The above code produces this output, without any need for binding new
names. So what is it you are actually trying to achieve, and why do you
think the new bindings are necessary?

-- 
 \        “The number of UNIX installations has grown to 10, with more |
  `\         expected.” —Unix Programmer's Manual, 2nd Ed., 1972-06-12 |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list