Python - can a dict have a value that is a list?

When using Python, is it possible that a dict can have a value that is a list?

for example, a dictionary that will look like this (see KeyName3 values):

{ keyName1 : value1, keyName2: value2, keyName3: {val1, val2, val3} } 

I already know that I can use 'defaultdict', however individual values ​​(understandably) are returned as a list.

The reason why I ask is because my code must be shared so that the caller can return the values ​​of one key as an element (exactly the same as from the value of the key of the key), and not as a list (without specifying pop[0] list) - however, also extract a few values ​​in the form of a list.

If not, then any suggestions would be welcome.

If someone can help, it will be great.

Thanks Advance,

Floor

* I am using Python 2.6, but I am writing scripts that should also be compatible with Python 3.0 +.

+8
python dictionary list key-value
source share
3 answers

Yes. The values ​​in dict can be any types of python objects. The keys can be any hashed object (which does not allow the list, but allows the tuple).

To create a list, use [] , not {} :

 { keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] } 
+24
source share

Yes, it is possible:

 d = {} d["list key"] = [1,2,3] print d 

exit:

 {'list key': [1, 2, 3]} 
+5
source share

It can definitely have a list and any object as a value, but a dictionary cannot have a list as a key, because the list is a mutable data structure, and the keys cannot be changed otherwise than they are.

0
source share

All Articles