Reputation: 97
This is my program so far. What I need to do is written in the 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
The Dictionary myIMBd
is currently empty. But what I need help with is the loop. When I try to do this in the runner.
addMovie("Shutter Island", ['Teddy Daniels','Crazy Lady'],['Leodnardo diCaprio', 'old actress'] )
I get an error that says
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'
Does that mean that I can't have a dictionary inside of a dictionary? If so, how do I change it from a dictionary to a non-dict. If I can have a dict inside a dict, why doesn't this work.
Upvotes: 0
Views: 145
Reputation: 168616
As others pointed out, you said ,
when you should have said :
.
Having said that, this version also works, but doesn't require the loop:
def addMovie (title, charList, actList):
return { title : dict(zip(charList, actList)) }
Upvotes: 0
Reputation: 3158
This is what you want :
def addMovie (title, charList, actList):
dict2 = {}
myDict={}
for i in range (0, len(charList)):
dict2 [charList[i]] = actList[i]
myDict[title] = dict2
return myDict
#printed for testing
print addMovie("Shutter Island", ['Teddy Daniels','Crazy Lady'],['Leodnardo diCaprio', 'old actress'] )
Upvotes: 0
Reputation: 4182
this is not dict
, rather set
myDict = {title, dict2}
You should use colon to create dict
myDict = {title: dict2}
But this exception can be related to dict
in dict
too
TypeError: unhashable type: 'dict'
If You try to use dict
as key of other dict
or as item of set
You wil get this error
Upvotes: 1
Reputation: 48725
You are creating a set
. Use this instead
myDict = {title: dict2}
A dict
in python is not hashable, and the requirement for something to be in a set is that it is hashable (that's how you can quickly tell from the error message what you did wrong). With the commas and no :
, what you wrote is the set
literal notation.
Also, dict
keys must be hashable, but that's not your issue.
Upvotes: 2
Reputation: 8492
You want something like:
myDict = {title: dict2}
What you've provided is actually Python's set literal.
Upvotes: 2