Discussion:
If a dictionary key has a Python list as its value!
(too old to reply)
Varuna Seneviratna
2024-03-07 14:11:11 UTC
Permalink
If a dictionary key has a Python list as its value, you can read the values
one by one in the list using a for-loop like in the following.

d = {k: [1,2,3]}
print(v)
No tutorial describes this, why?
What is the Python explanation for this behaviour?

Varuna
MRAB
2024-03-07 18:23:46 UTC
Permalink
Post by Varuna Seneviratna
If a dictionary key has a Python list as its value, you can read the values
one by one in the list using a for-loop like in the following.
d = {k: [1,2,3]}
print(v)
No tutorial describes this, why?
What is the Python explanation for this behaviour?
If the value is a list, you can do list things to it.

If the value is a number, you can do number things to it.

If the value is a string, you can do string things to it.

And so on.

It's not mentioned in tutorials because it's not special. It just
behaves how you'd expect it to behave.
Mats Wichmann
2024-03-07 18:29:07 UTC
Permalink
Post by Varuna Seneviratna
If a dictionary key has a Python list as its value, you can read the values
one by one in the list using a for-loop like in the following.
d = {k: [1,2,3]}
print(v)
No tutorial describes this, why?
What is the Python explanation for this behaviour?
Sorry... why is this a surprise? If an object is iterable, you can
iterate over it.
Post by Varuna Seneviratna
d = {'key': [1, 2, 3]}
type(d['key'])
<class 'list'>
Post by Varuna Seneviratna
val = d['key']
type(val)
<class 'list'>
... print(v)
...
...
1
2
3
Stefan Ram
2024-03-07 19:21:31 UTC
Permalink
Post by Varuna Seneviratna
If a dictionary key has a Python list as its value, you can read the values
one by one in the list using a for-loop like in the following.
d = {k: [1,2,3]}
print(v)
No tutorial describes this, why?
What is the Python explanation for this behaviour?
This is explained by extensionality: To find the behavior of
"for v in ...", the only thing one needs to know about "..."
is its value. You could just as well have written:

l = d[ k ]
for v in l:

. l can be any iterable. It does not matter where it came from.
It does not matter that it cam from a dictionary. There are thousand
places where it could have come from, and no tutorial can name them
all.

Loading...