I am playing about with Python, trying to understand dictionaries. I know questions have been asked before relating to this error, but they don't help me understand my issue.
I have the following code
mailSender = dict()
count = 0
name = input("Enter file:")
handle = open(name)
for line in handle:
line = line.rstrip()
if not line.startswith("From "):
continue
count = count + 1
senderNames = line.split()
# print(splitLines[1])
print(senderNames[1])
if senderNames not in mailSender:
mailSender[senderNames] = 1
else:
mailSender[senderNames] = mailSender[senderNames] + 1
# print(mailSender)
I am trying to pick out email addresses for a text file,a nnd then find who sent the most emails.
I keep getting the following error:
if senderNames not in mailSender: TypeError: unhashable type: 'list'
I do not have the experience to see where I am going wrong, and I hope someone can shed some light on it.
A dictionary has 2 parts, keys
and values
. Each key
, points to a value
, which is done like so:
mailSender["email@email.com"] = 5 # This means, that email@email.com appears 5 times
When you are trying to look for the name of a sender, you need to search for the name in the keys
where all the emails are stored, not the entire dictionary, which is a mapping for keys
to values
. You also need to indicate the position of the email address you want to find in senderNames
, which is 1 of the list of emails. You can solve your problem, by changing your code to:
if senderNames[*index of name*] not in mailSender.keys():
mailSender[senderNames] = 1
else:
mailSender[senderNames] = mailSender[senderNames] + 1
For example, you could refer to finding the first email address like this:
if senderNames[0] not in mailSender.keys():
mailSender[senderNames] = 1
else:
mailSender[senderNames] = mailSender[senderNames] + 1
It will then search for if senderNames
is in the keys of mailSender
. Hope this helped!