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

68,142

Solution 1

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] }

Solution 2

Yes, it's possible:

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

output:

{'list key': [1, 2, 3]}
Share:
68,142
Paul Kernaghan
Author by

Paul Kernaghan

Updated on April 29, 2020

Comments

  • Paul Kernaghan
    Paul Kernaghan about 4 years

    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+.

  • Paul Kernaghan
    Paul Kernaghan almost 13 years
    Doh! That's worked perfectly. Thanks for your help and greatly appreciated.
  • Marcin
    Marcin over 12 years
    The reason why one can use a tuple but not a list is because lists are mutable, so any calculation based on their "value" would not be idempotent (computing sense).
  • Eswemenasja
    Eswemenasja over 6 years
    @geoffspear, Cool but how to get value by keyname3 and list value 2?
  • Wooble
    Wooble over 6 years
    @Eswemenasja yourdict["keyname3"][2]
  • jake wong
    jake wong over 5 years
    How do you unpack keyName3 though? Such that val1 val2 val3 will have keyName3 in it?