Why isn't this code working how I want it to?
Marco Nawijn
nawijn at gmail.com
Sat Oct 12 05:17:53 EDT 2013
On Saturday, October 12, 2013 10:56:27 AM UTC+2, reuben... at gmail.com wrote:
> I've been working on a program and have had to halt it due a slight problem. Here's a basic version of the code:
>
>
>
> a = 'filled'
>
> b = 'filled'
>
> c = 'empty'
>
> d = 'empty'
>
> e = 'filled'
>
> f = 'empty'
>
> g = 'filled'
>
>
>
> testdict = {a : 'apple' , b : 'banana' , c : 'cake' , d : 'damson' , e : 'eggs' , f : 'fish' , g : 'glue'}
>
>
>
>
>
> Now what I want to do, is if a variable is filled, print it out. This however isn't working how I planned. The following doesn't work.
>
>
>
> for fillempt in testdict:
>
> if fillempt == 'filled':
>
> print(testdict[fillempt])
>
>
>
> All this does though, is print glue, where I'd want it to print:
>
>
>
> apple
>
> banana
>
> eggs
>
> glue
>
>
>
> Perhaps a dictionary isn't the best way to do this.. I wonder what else I can do...
>
>
>
> Thanks for any help.
Hi,
Remember that keys in a dictionary are unique. So if you defined (>>> means it I typed it at the interactive terminal prompt,
>>> d = { 'filled' : 'apple' , 'filled' : 'orange' }
and do a
>>> print d
it will show:
>>>
{'filled': 'orange'}
One way to solve this problem is to define two dictionaries.
One holding the status of the variable, the other one holding
the data. For example:
status = { 'a' : 'filled', 'b' : 'empty', 'c' : 'filled' }
data = { 'a' : 'orange', 'b' : 'apple', 'c' : 'banana' }
for k in status:
if status[k]=='filled':
print data[k]
Regards and let us know if it works for you,
Marco
More information about the Python-list
mailing list