Why variable[variable] brings value from a dictionary?

What is the mechanism behind this code?

pocet_piv = { 'Petr' : 6 , 'Pavel' : 7, 'Martin': 4}
for whatever in pocet_piv:
    print(whatever, pocet_piv[whatever])

I would expect that pocet_piv[whatever] brings me a key from the dictionary, not the value. Who devised the logic for it to come up with the value, and why?

Why would you expect that?

Iterating through a dict yields its keys in insertion order. dictionary[key] returns the value corresponding to key.

1 Like

Because for loop iterates over keys. So pocet_piv[whatever] looks for keys in pocket_piv. That would me my understanding.

Correct.

That makes no sense. whatever is already a key, per your previous sentence.

1 Like

Yup, if whatever is already the key so print(pocet_piv[whatever]) would print the key in pocet_piv dictionary. So the question is, how was born the logic it prints the value.

Let’s take a step back.

d = {"key": "value"}
print(d["key"])

What do you think this will print?

1 Like

I think it will print "value".

Correct. So why would would you expect it to behave differently in your example above?

2 Likes

Some glimpse of it from Raymond Hettinger’s Transforming Code into Beautiful, Idiomatic Python - Dictionary skills

Keys in dictionary are similar to indexes in ordered sequences differences being that keys can be arbitrary hashable values whether indexes are sequential integers starting from zero.

items = ['bacon', 'ham', 'spam']
items[0]

# should it return 0 or 'bacon'?
# if 'bacon' why should dictionary keys be different?
# if 0 then how 'bacon' is accessible?
1 Like

What would that look like? What should be printed?

I’m not sure if this is an issue of mixed-up terminology or something else.

4 Likes

Yeah, I guess this is the type of answer I was looking for. Thx.