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

前端 未结 3 1826
甜味超标
甜味超标 2020-12-17 16:14

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):<

相关标签:
3条回答
  • 2020-12-17 16:29

    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] }
    
    0 讨论(0)
  • 2020-12-17 16:35

    It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

    0 讨论(0)
  • 2020-12-17 16:39

    Yes, it's possible:

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

    output:

    {'list key': [1, 2, 3]}
    
    0 讨论(0)
提交回复
热议问题