I can get no satisfaction ...... from keys and values!


#1

Ok, maybe this is a very simple question, but I would really appreciate some feedback on it.

I'm stuck at a day at the Supermarket even though I got the code to work. Here's my big deal:

def compute_bill(food):
---total = 0
---for key in food:
-----total = total+prices[key]
---return total

When I use a for loop in this case.. Python will add the prices -key- from my looped items in 'food'

Now, my dictionary is this... prices = {'banana' = 4, 'apple' = 2... and so on...
Isn't the number 4 supposed to be the value of my entry?
I mean... for the purpose of a dictionary, wouldn't it be wrong if I had 2 entries with the same key?? and if the price itself is the key, there might be two items with the same price... or key in this case??

The real deal here for me is that I am convienced that 4 is a value not a Key..... is the value for the entry 'banana'

Do I sound crazy?? I feel kinda stupid but this is my thinking...... :sweat:


#2

No equals signs in a dictionary. Use key : value, pairs...

prices = {'banana': 4, 'apple': 2, ...

Yes, but it won't raise an exception. Dictionaries are sets and can only have discrete keys The latter key and associated value would be the one registered. That does not stop multiple dictionaries having the same keys in common. There is no conflict and it sets up the exact scenario we are working in. The two (or more) dictionaries are relational.

Values on the other hand, they can be duplicated without concern. Lots of entries can have a value of '4'.

I'm finding the question a little confusing so a sketch will illustrate...

    obj = {
        class: 'Dict',
        type: 'dict',
        # key: value
    }

An anonymous dictionary expression given two properties, class and type are the key names, Dictionary and dictionary are the values.

>>> obj['type']
dict
>>> obj['class']
Dict

#3

You are correct, 4 is the value, banana is the key. However, in the for loop "key" is being used to access the value. We could use any word we wanted in the for, its just a temporary variable. If you wanted to you could say
for value in food:
total = total += prices[value]
`


#4

Thanks so much for the prompt response!! And I assumed what you've just said, thing is I tried it and it didn't work so I was really confused. I'm new to this coding thing and I have no experience at all with scripts, for loops were really confusing :confused:.
Thanks again for your help.


#5

Yeah, newbie mistake, noted!! I was just trying to explain myself. Thanks for the heads up anyway!


#6

In what way did it not work? I just tried it with my code and it ran fine.


#7

Yeah, it worked... I must have missed some spelling mistake..
thanks again!


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.