Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 would look like the following (see KeyName3's values):

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

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

The reason I ask is that my code must be generic so that the caller can retieve single key values as an item (just like from a dict key-value) and not as list (without having to specify pop[0] the list) - however also retrieve multiple values as a list.

If not then any suugestions would be welcome.

If someone can help then that would be great.

Thanks in Advance,

Paul

*I'm using Python 2.6 however writing scripts that must also be forward compatible with Python 3.0+.

like image 297
Paul Kernaghan Avatar asked Jul 05 '11 19:07

Paul Kernaghan


People also ask

Can a dict have a list as value?

Here the default dict() method is used to iterate over a list of tuples. In this example, we have inserted a list as a value in the dictionary by applying the method subscript. In a Python dictionary, the subscript method can be added to an existing value and can be modified to a Python dictionary.

Can a dictionary have a list as a key?

A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.

How do I use a list inside a dictionary in Python?

Let's see all the different ways we can create a dictionary of Lists. Method #2: Adding nested list as value using append() method. Create a new list and we can simply append that list to the value. Iterate the list and keep appending the elements till given range using setdefault() method.


2 Answers

Yes. The values in a dict can be any kind of python object. The keys can be any hashable object (which does not allow a list, but does allow a tuple).

You need to use [], not {} to create a list:

{ keyName1 : value1, keyName2: value2, keyName3: [val1, val2, val3] }
like image 124
Wooble Avatar answered Oct 19 '22 18:10

Wooble


Yes, it's possible:

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

output:

{'list key': [1, 2, 3]}
like image 43
GreenMatt Avatar answered Oct 19 '22 19:10

GreenMatt