On 17/05/16 23:56, Chris Kavanagh wrote:

> So, by putting quotes around a dict key, like so dict["key"] or in my case
> cart["item"] this makes the dict have ONE key. The loop assigns the
> cart_items to this ONE key until the end of the loop, and I'm left with
> {'item': 5}. . .
> 
> Where as if you do NOT put the key in quotes, dict[key] or cart[item], this
> basically means the dict has as many keys as you're iterating through. In
> other words it assigns the cart_item as a key and a value, and saves them
> all to the dict.
> 
> Is that correct?

Sort of, but not for the reasons you give.
Putting the key in quotes makes it a literal string.
That is, a fixed value, just like 2 or 5.5 or True.
These are literal integer, float and boolean values
respectively.

So you could just as well have done:

for item in cart_items:
    cart[2] = item

And everything would be stored under a key of 2.

Or

for item in cart_items:
    cart[True] = item

And everything would get stored on a key of True.

The quotes turn the sequence of characters 'i','t','e','m'
into the string value 'item'. The fact that the string is
the same as the variable name in your for loop is completely
coincidental. Python doesn't recognise them as in any way
related.

So in the first case the issue is that you stored your
values in a single unchanging key.

Whereas in the second loop you stored your values against
a key which was a variable that changed in each iteration.

The fact you used quotes is only significant in that quotes
are what you use to create a literal string value. But it
was the fact that it was a fixed value that made everything
appear in the same place (and hence be overwritten), not the
quotes per se.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to