here’s the message :
Traceback (most recent call last):
File “C:\Users\Giroux\Desktop\Coding\Python\Py4e\03 - 01 EX - Python for Everybody Course\EX7-1\eexc-chap9.py”, line 25, in
emails[email] = emails.get(email,0) + 1
TypeError: descriptor ‘get’ for ‘dict’ objects doesn’t apply to a ‘str’ object
here’s my code:
fname = input("enter file: ")
try:
hand = open(fname)
except:
print(“file cannot be read”,fname)
exit()
emails = dict
for li in hand:
if li.startswith("From "):
li = li.split()
email = li[1]
emails[email] = emails.get(email,0) + 1
emails = dict assigns dict type to emails variable. That makes using emails equivalent of using dict, and emails.get(email, 0) is like writing dict.get(email, 0).
This is not correct (and this applies to usage of any class really), when dictionary instance uses get method it implicitly passes itself as a first argument. As in here there’s no instance here, the get method needs to have instance passed explicitly, ie. dict.get(dictionary, email, 0). Since in the code first argument is variable pointing to string TypeError is raised.