For Loop List - how to get the value for the dictionary to append to List

https://app.dataquest.io/m/355/list-comprehensions-and-lambda-functions/5/using-list-comprehensions-to-transform-and-create-lists

At this stage, i am still taking guess shots at how to append to a List using a For Loop. :slight_smile:

In the mission above, i tried to construct the For Loop using the code below.

urls =
for iter in hn_clean:
urls.append(hn_clean[“url”])

The right answer is

urls =
for iter in hn_clean:
urls.append(iter[“url”])

From which, i get the error message


TypeError Traceback (most recent call last)
in
2 # What I did Wrong
3 for iter in hn_clean:
----> 4 urls.append(hn_clean[“url”])

TypeError: list indices must be integers or slices, not str

Can someone walk through with me, what’s the difference between

urls.append(hn_clean[“url”]

versus

urls.append(iter[“url”])

I have checked Iterator in For-loops and also How does a For Loop Work? but thought that it

If it is answered somewhere else in this forum, would appreciate it if can point me the right link please :slight_smile:

Hey @willx. hn_clean in this mission is a list where each item in the list is a dictionary. When we’re calling items in a list, we use their index numbers. For example, hn_clean[0] returns the first dictionary:

{'author': 'dragongraphics',
 'createdAt': '2014-05-29T08:07:50Z',
 'numComments': 0,
 'objectId': '7815238',
 'points': 2,
 'storyText': '',
 'tags': ['story', 'author_dragongraphics', 'story_7815238'],
 'title': 'Are we getting too Sassy? Weighing up micro-optimisation vs. maintainability',
 'url': 'http://ashleynolan.co.uk/blog/are-we-getting-too-sassy'}

However, this isn’t what we want. We want to get to the 'url' key of EACH dictionary so that we can create a separate list of URLs. This is where we use the loop. for iter in hn_clean: will go through each item in the hn_clean list. iter for each iteration is a dictionary, so to extract the information we use the dictionary name (in this case iter from the loop) and the key 'url'. Then we append iter['url'] to the new list urls.

I hope that clears things up!

2 Likes

ah got, thank you so much for the beautiful explanation. :grinning:

2 posts were split to a new topic: 312-9 Lists and loops error question