[Tutor] Adding to a dict through a for loop confusion.

Chris Kavanagh ckava3 at gmail.com
Tue May 17 04:28:12 EDT 2016


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

print cart

#output
{'item': 5}

------------------------------------------------------------------------------------------------------------------------------------------------
# Example #2
cart_items = ['1','2','3','4','5']

cart = {}

for item in cart_items:
    cart[item] = item

print cart

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


Thanks you for the help.


More information about the Tutor mailing list