Re: [Tutor] enumerate over Dictionaries

2019-07-04 Thread Alan Gauld via Tutor
On 04/07/2019 18:02, Animesh Bhadra wrote:
> Hi All,
> My python version is 3.6.7
> I need help to understand this piece of code?
> 
> rainbow ={"Green": "G", "Red": "R", "Blue": "B"}
> # ennumerate with index, and key value
> for i, (key, value) in enumerate(rainbow.items()):

Lets unpick t from the inside out.
What does items() return?

>>> rainbow.items()
dict_items([('Green', 'G'), ('Red', 'R'), ('Blue', 'B')])

For our purposes dict_items is just a fancy kind of list.
In this case it is a list of tuples. Each tuple being
a key,value pair.

What does enumerate do to a list?
It returns the index and the value of each item in the list.
So if we try

>>> for index, val in enumerate(rainbow.items()):
 print( index, val)

0 ('Green', 'G')
1 ('Red', 'R')
2 ('Blue', 'B')

We get the 0,1,2 as the index of the 'list' and the
corresponding tuples as the values.

Now when we replace val with {key,value) Python performs
tuple unpacking to populate key and value for us.

> print(i, key, value)

So now we get all three items printed without the tuple parens.
Which is what you got.

> This gives a output as always:-
> 
> 0 Green G
> 1 Red R
> 2 Blue B


> Does this means that the Dict is ordered? or it is implementation dependent?

Neither, it means the items in a list always have indexes
starting at zero.

By pure coincidence dictionaries in recent Python versions (since 3.6
or 3.7???) retain their insertion order. But that was not always the
case, but the result would have been the same so far as the 0,1,2 bit goes.

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


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] enumerate over Dictionaries

2019-07-04 Thread Animesh Bhadra

Hi All,
My python version is 3.6.7
I need help to understand this piece of code?

rainbow ={"Green": "G", "Red": "R", "Blue": "B"}
# ennumerate with index, and key value
fori, (key, value) inenumerate(rainbow.items()):
print(i, key, value)


This gives a output as always:-

0 Green G
1 Red R
2 Blue B


Does this means that the Dict is ordered? or it is implementation dependent?


Thanks & Regards,
Animesh.





___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor