Python:字典中的字典

2024-04-19 05:03:58 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前的节目。我需要做的是写在docString中。你知道吗

#string, list, list --> Dictionary
def addMovie (title, charList, actList):
    """The function addMovie takes a title of the movie, a list of characters,
    and a list of actors. (The order of characters and actors match one
    another). The function addMovie adds a pair to myIMDb. The key is the title
    of the movie while the value is a dictionary that matches characters to
    actors"""

    dict2 = {}
    for i in range (0, len(charList)):
        dict2 [charList[i]] = actList[i]

    myDict = {title, dict2}
    return myDict

词典myIMBd当前为空。但我需要的是循环。当我试着在跑步者身上这样做的时候。你知道吗

addMovie("Shutter Island", ['Teddy Daniels','Crazy Lady'],['Leodnardo diCaprio', 'old actress'] )

我得到一个错误说

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
addMovie("Shutter Island", ['Teddy Daniels','Crazy Lady'],['Leodnardo diCaprio', 'old actress'] )
File "C:\Python33\makeDictionary.py", line 10, in addMovie
myDict = {title, dict2}
TypeError: unhashable type: 'dict'

那是不是意味着我不能在字典里放一本字典?如果是的话,我怎么把它从字典改成非dict呢?如果dict里面有dict,为什么不起作用呢。你知道吗


Tags: ofthein字典titleactorsdictmydict
3条回答

你想要的是:

myDict = {title: dict2}

您提供的实际上是Python的set literal。你知道吗

这不是dict,而是set

myDict = {title, dict2}

您应该使用冒号来创建dict

myDict = {title: dict2}

但是这个异常也可能与dict中的dict有关

TypeError: unhashable type: 'dict'

如果您试图将dict用作其他dict的键或set的项,则会出现此错误

您正在创建set。改用这个

myDict = {title: dict2}

python中的dict是不可散列的,对集合中的某些内容的要求是它是可散列的(这就是如何从错误消息中快速判断您做错了什么)。使用逗号和no:,您编写的是set文字表示法。你知道吗

另外,dict键必须是可哈希的,但这不是您的问题。你知道吗

相关问题 更多 >