Mounarajan Mounarajan - 5 months ago 7
Python Question

some random error in python dictionary

I get some random error while printing results from python dictionary

code

response_str = {'personal_emails': [{'email_address': 'hi'}]}


email_f = []
email_s = []
email_h = []

email_s = response_str["personal_emails"]
#print response_str
#print email_s
for email_1 in email_s:
print email_1
if email_1["confidence_score"] == "50":
print email_1["email_address"]
email_f.append(email_1["email_address"])
if email_1["confidence_score"] == "75":
print email_1["email_address"]
email_s.append(email_1["email_address"])
if email_1["confidence_score"] == "100":
print email_1["email_address"]
email_h.append(email_1["email_address"])


Error:

File "emai_sep.py", line 13, in <module>
if email_1["confidence_score"] == "50":
TypeError: string indices must be integers, not str


How to fix this error?

Answer

The problem here is because of this line:

email_s.append(email_1["email_address"])

This is the list the iterator runs on, and during the iterations you change it.

when I ran this code after comment that line out it ran smoothly.

So, my suggestion is you use another list to append 'email_addresses' to, like this:

response_str = {'personal_emails': [{'email_address': 'karogers826@gmail.com', 'confidence_score': '75'}, {'email_address': 'plushpalcreations@gmail.com', 'confidence_score': '50'}, {'email_address': 'poet@gmail.com', 'confidence_score': '50'}, {'email_address': 'kristen.the.poet@gmail.com', 'confidence_score': '75'}]}


email_f = []
email_s = []
email_h = []
email_s_NEW = [] # NEW LIST

email_s = response_str["personal_emails"]
#print response_str
#print email_s
for email_1 in email_s:
    print email_1
    if email_1["confidence_score"] == "50":
        print email_1["email_address"]
        email_f.append(email_1["email_address"])
    if email_1["confidence_score"] == "75":
        print email_1["email_address"]
        email_s_NEW.append(email_1["email_address"]) # APPEND TO THIS LIST
    if email_1["confidence_score"] == "100":
        print email_1["email_address"]
        email_h.append(email_1["email_address"])