On 17May2016 04:28, Chris Kavanagh <cka...@gmail.com> wrote:
Could someone tell me why this different behavior occurs between these 2
code snippets, please. The 1st example has quotes around it ['item'] only
adds the last item to the dict (cart). In the 2nd example the item does not
have quotes around it [item] and every entry is added to the dict.

Why?
[...]
# Example #1
cart_items = ['1','2','3','4','5']
cart = {}
for item in cart_items:
   cart['item'] = item

This for loop assigns the values '1','2','3','4','5' in succession to the variable named "item". Then the body of the loop assigns that value (via the variable "item") to the single dictionary slot with the fixed key with string value 'item' i.e. always the same slot. And the last item is the one kept. All the earlier assignments are overwritten by the later ones: they happen, but are replaced.

print cart
#output
{'item': 5}

Which you see above.

# Example #2
cart_items = ['1','2','3','4','5']
cart = {}
for item in cart_items:
   cart[item] = item

Here, the variable named "item" takes on the values as before, but the diction slot chosen also comes form that variable. So each value ends up in its own slot as your output shows.

print cart
# output
{'1': '1', '3': '3', '2': '2', '5': '5', '4': '4'}

The essential difference here is that in the first example the expression for the slot in the dictionary is the expression:

 'item'

which is simply the fixed string 'item'. In the second example the expression is:

 item

which produces the current value stored in the variable "item".

Cheers,
Cameron Simpson <c...@zip.com.au>
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to