Hello,
Am 17.05.2016 um 10:28 schrieb Chris Kavanagh:
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}
Here you assign every item from your list to a dictionary entry with the
same key 'item' - that's a string literal that hasn't got anything to do
with the name item you give to each list element in turn.
Because a dictionary can only contain one entry for each key the value
of that entry cart['item'] is overwritten in every step through the
loop. Only the result of the last step is kept.
------------------------------------------------------------------------------------------------------------------------------------------------
# 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'}
Here you take the value from the list cart_items, called item, for the
key and for the value of the dictionary entry. So every entry gets a
different key and your dictionary has as many entries as the list has
elements.
But did you really want to get a dictionary with the same values for key
and value?
HTH
Sibylle
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor