How Do You Replace Variables With Their Values?

Frank Millman frank at chagford.com
Thu Jul 11 00:59:03 EDT 2019


On 2019-07-11 12:43 AM, CrazyVideoGamez wrote:
> How do you replace a variable with its value in python 3.7.2? For example, say I have:
> 
> 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():
>          meal = list(dinner[meal])
> 
> But I only get one list called "meal" and I'm just changing it with the code above (you can find that by printing it out). How can I make separate lists called 'Starters', 'Main Course', and 'Desert'?
> 

1. Iterating over a dictionary returns each key. So instead of 'for meal 
in dinner.keys()' you can just say 'for meal in dinner'.

2. It is not a good idea to use the variable name 'meal' for two 
purposes. You use it to get each key, and then it gets over-ridden with 
the result of 'list(dinner[meal])'. Then on the next iteration it gets 
over-ridden again with the next key.

3. The result of 'dinner[meal]' is already a list, so there is no need 
to say 'list(dinner[meal])'. Technically there is a difference - your 
approach creates a new list, instead of just creating a reference to the 
original one, but I doubt if that was your intention.

4. There is potentially more than one list, but for each iteration you 
over-ride the previous one, so at the end, only the last one remains. 
The solution is to create a 'list of lists'.

Putting all this together -

     courses = []
     for course in dinner:
         courses.append(dinner[course])

This gives you a list, called 'courses', containing three lists, one for 
each 'course' containing the options for that course.

However, in the process, you have lost the names of the courses, namely 
'Starters', 'Main course', and 'Desert'.

So to answer your original question "How can I make separate lists 
called 'Starters', 'Main Course', and 'Desert'?", the code that you 
started with is exactly what you asked for.

I think you were asking how to create a variable called 'Starters' 
containing the list of starters. It can be done, using the built-in 
function 'setattr()', but I don't think that would be useful. If you 
knew in advance that one of the options was called 'Starters', you could 
just say Starters = ['Fried Calamari', 'Potted crab']. But if you did 
not know that in advance, how would you know what your variable was called?

Frank Millman



More information about the Python-list mailing list