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

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 17 05:04:25 EDT 2016


On 17/05/16 09:28, Chris Kavanagh wrote:

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

'item' is a literal string. It never changes.
So you keep overwriting the dict entry so that
at the end of the loop the dict contains the
last value associated with your literal key 'item'

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

here you use the actual item from your data as both
the key and the value. So you wind up with a dict
containing a key/value pair for each value in your
data list.

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

That's not a very common requirement though, usually
you would have different values from the keys.

Maybe something like:

for item in cart_items:
    cart[item] = int(item)

which stores an integer value against the string
representation:

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

Notice also that dicts don't usually print out
in the same order as you created them. In fact
the 'order' can even change over the life of your
program, as you add/remove elements.

-- 
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




More information about the Tutor mailing list