Help understanding this for loop

This is the place for queries that don't fit in any of the other categories.

Help understanding this for loop

Postby phalse » Wed Jun 11, 2014 1:58 pm

Hello all I am still pretty new in python and need some help decomposing this statement. If someone could break it down for me that would be very helpful. Thanks!

ob = {a[1]:i for i, a in enumerate(ob.fields)}
phalse
 
Posts: 4
Joined: Mon Jul 01, 2013 1:55 pm

Re: Help understanding this for loop

Postby Kebap » Wed Jun 11, 2014 3:24 pm

Hi! Uhm, yeah, which part did you understand, and which other parts do you still have questions about?

Do you know python lists and dictionaries? Have you looked at an explanation for enumerate()? Etc.
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 403
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Re: Help understanding this for loop

Postby phalse » Wed Jun 11, 2014 4:22 pm

Sorry, I guess I understand what the for a,i in enumerate does, but I don't understand the first part {a[1]:i does. I feel like there is some shorthand at play that I don't get. Is there another way of writing this?
phalse
 
Posts: 4
Joined: Mon Jul 01, 2013 1:55 pm

Re: Help understanding this for loop

Postby Mekire » Wed Jun 11, 2014 4:34 pm

So lets say fields is this:
Code: Select all
fields = [("Ringo","Star"), ("Mary","Tyler"), ("Joe","Shmoe")]

The comprehension here:
Code: Select all
ob = {a[1]:i for i,a in enumerate(fields)}

Is equivalent to this:
Code: Select all
ob = {}
for i,a in enumerate(fields):
    last_name = a[1]
    ob[last_name] = i

In this example we create a dictionary of the last names in fields with values being the location they are in the list.
Code: Select all
{'Shmoe': 2, 'Star': 0, 'Tyler': 1}

-Mek
User avatar
Mekire
 
Posts: 1140
Joined: Thu Feb 07, 2013 11:33 pm
Location: Asakusa, Japan

Re: Help understanding this for loop

Postby phalse » Wed Jun 11, 2014 7:02 pm

Ahhh, thank you so much! That was exactly what I was looking for.
phalse
 
Posts: 4
Joined: Mon Jul 01, 2013 1:55 pm

Re: Help understanding this for loop

Postby XndrK » Wed Jun 11, 2014 8:40 pm

Mek:

You misspelled Ringo Starr's name (two r's in Starr). ಠ_ಠ
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 173
Joined: Sat Jun 15, 2013 7:57 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 3 guests