[REQUEST-ELI5] How this for-in works?
Hi, people!
I'm doing the University of Michigan's Introduction to Data Science in Python course and I'm finding one particular line on their Jupyter notebook hard to understand.
There is a list of dictionaries with fuel consumption and other cars data.
print(mpg[0])
{'': '1', 'year': '1999', 'cty': '18', 'class': 'compact', 'trans': 'auto(l5)', 'model': 'a4', 'manufacturer': 'audi', 'fl': 'p', 'hwy': '29', 'drv': 'f', 'displ': '1.8', 'cyl': '4'}
There are some examples of what to do with this data and how to accomplish them. But I'm puzzled on how do they calculate average mpg:
sum(float(d['cty']) for d in mpg) / len(mpg)
Sure thing, they got the desired result. The thing is, I kinda know what's going on on that line but I don't really know or can explain. I get the interpreter is using d for each item in mpg(mpg.items) but I don't how the first d['cty'] works.
So the question is what the d['cty'] piece of the for statement do, how it works and what the interpreter actually does with that piece of the statement?
Sidenote, I have done:
a=0
for i in mpg:
a += float(i['cty'])
print(a/len(mpg))
And while it works just fine, it doesn't seem as pythonic as the lecturer way of do it.
Thanks in advance!
EDIT: formatting.