Thank you so much for the help, and the example! 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? On Tue, May 17, 2016 at 5:01 AM, <c...@zip.com.au> wrote: > 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