Lem
Lem

Reputation: 79

Are these two python for-loops the same thing?

I'm going over a video tutorial and I was caught off guard with a for-loop being in a dict() command. I had a hard time googling things on the dict() command (kept getting definitions on dictionaries and not the command) so I'm now assuming I can add for-loops into commands.

In the video they use

dict((m[:3].lower(),m) for m in months)

so I'm curious if that is the same as

for m in months:
    variable = dict((m[:3].lower(),m))

Here's the video for reference https://youtu.be/a2sLiEgBl9k?t=1m17s

Upvotes: 1

Views: 69

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1123400

No, that's not the same.

Your version creates a new dictionary object each iteration, with just one key and value. The version in the video creates one dictionary object with a series of key-value pairs.

The version in the video is equivalent to:

d = {}
for m in months:
    d[m[:3].lower()] = m

but is using a generator expression to produce the key-value pairs (as tuples) in a loop instead. The dict() object takes each such pair and adds them to the dictionary being constructed.

and in Python 2.7 and newer could also be written with a dictionary comprehension:

{m[:3].lower(): m for m in months}

The end result is a dictionary with the first three letters of each month (lowercased) as the key:

>>> import calendar
>>> months = calendar.month_name[1:]
>>> {m[:3].lower(): m for m in months}
{'mar': 'March', 'feb': 'February', 'aug': 'August', 'sep': 'September', 'apr': 'April', 'jun': 'June', 'jul': 'July', 'jan': 'January', 'may': 'May', 'nov': 'November', 'dec': 'December', 'oct': 'October'}
>>> pprint(_)
{'apr': 'April',
 'aug': 'August',
 'dec': 'December',
 'feb': 'February',
 'jan': 'January',
 'jul': 'July',
 'jun': 'June',
 'mar': 'March',
 'may': 'May',
 'nov': 'November',
 'oct': 'October',
 'sep': 'September'}

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117926

This expression is creating a dict using a generator expression.

d = dict((m[:3].lower(),m) for m in months)

is equivalent to

d = dict()
for m in months:
    d[m[:3].lower()] = m

You second loop is not doing the same thing. You are iterating over each month, then creating a dict with a single entry and assigning it to variable. This variable is being overwritten each iteration.

From looking at the code, they are trying to make such a dictionary:

{'jan': 'January',
 'feb': 'February',
 'mar': 'March',
 ...
}

Upvotes: 3

Related Questions