Mailing List Archive

If a dictionary key has a Python list as its value!
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]}


> for v in d[k]:
> print(v)


No tutorial describes this, why?
What is the Python explanation for this behaviour?

Varuna
--
https://mail.python.org/mailman/listinfo/python-list
Re: If a dictionary key has a Python list as its value! [ In reply to ]
On 2024-03-07 14:11, Varuna Seneviratna via Python-list wrote:
> 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]}
>
>
>> for v in d[k]:
>> 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.
--
https://mail.python.org/mailman/listinfo/python-list
Re: If a dictionary key has a Python list as its value! [ In reply to ]
On 3/7/24 07:11, Varuna Seneviratna via Python-list wrote:
> 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]}
>
>
>> for v in d[k]:
>> 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.

>>> d = {'key': [1, 2, 3]}
>>> type(d['key'])
<class 'list'>
>>> val = d['key']
>>> type(val)
<class 'list'>
>>> for v in val:
... print(v)
...
...
1
2
3
>>>



--
https://mail.python.org/mailman/listinfo/python-list