3.Extracting all keys (PP)

Screen Link:

My Code:

keys = []
for key in people:
    keys.append(key)
    
print(keys)

What I expected to happen:
I got the answer right. However i didnt understood the alternative reply given in answer.

Alternative answer 1

keys = [name for name in people]

Alternative answer 2

keys = list(people.keys())
it would be great if someone helps with these alternate solution. Thanks guys.

Alternative 1:

This method is called list comprehension. It does the exactly same thing as your code, but with one line of code only. The for inside the list works just like the one in your code.

Dataquest has a lesson on that in the Data Cleaning in Python: Advanced course.

Alternative 2:

people is a dictionary, therefore you can use the keys() method to get an object with all the keys in this dictionary. Then you use list() to transform the object with all the keys into a list.

1 Like

Ok i get it now after your explanation. Thanks a lot for the quick reply. Have a nice day/night :slight_smile:

1 Like