Python fundamental exercise. Dictionaries. 3/13

Screen Link:

Hi,
I did the code right but I don´t really understand what happens when you call a key in a dictionary

My Code:

 people = {"Katherine Freeman": "[email protected]","Tammy Gonzalez": "[email protected]","Robin Matthews": "[email protected]","Sherry Farrell": "[email protected]","Emma Graves": "[email protected]","Tina Brown": "[email protected]","George Owens": "[email protected]","Ronald Ball": "ronald.ba[email protected]"}
    keys=[]
    for name in people:
        keys.append(name)

['Katherine Freeman', 'Emma Graves', 'Ronald Ball', 'Tammy Gonzalez', 'Robin Matthews', 'Sherry Farrell', 'Tina Brown', 'George Owens']```

How does it Python knows that I´m calling the key but not the value? I can´t find anything clear in the course.

2 Likes

Hi @javiermarzalb

You can actually use

for name in people.keys():
        keys.append(name)

to specify the dictionary key . But by default for loop does that for you and loops through the keys of the dictionary when for loop is used.

You might find more information here

1 Like

That’s completely determined by how the programming language was designed. This is not really something we need to worry about since it starts going into the territory of how python works “behind-the-scenes”.

But, if you are interested in the finer details, you can go through this - https://realpython.com/python-for-loop/.

It explains how python loops works, and get an idea of how then python loops over dictionaries as well.
You can also iterate over the values of the dictionary but the syntax changes (which is also covered in the link I shared)

1 Like

This could be relevant when you use pandas in future: Why is `in` membership check searching in pd.Series keys rather than values

When we write our own objects and define how it can be iterated through, we can define the __iter__(self) method and code custom logic. This allows things like not raising StopIteration when you reach the end but jumping back to start to restart again, or to jump forward 2 elements each step rather than 1.

If you want to see how dictionaries are doing it, you may have to dive down to Cython.
My guess is data structure designers see it more useful to iterate through the keys by default than values because you can get values from keys, but not vice versa.

1 Like