How to avoid “key error” in python for loop?

I am new to python and I am trying to conduct multiple PubMed searches and save the number of results in a CSV file. The code I have right now as-is will run, but it only does one set of search terms and I would like the code to instead run through a column of “Terms” provided in a CSV file, but I don’t know what location to place the for loop, and I don’t know how to…I guess set the variable for the loop to run. Here is what I have that runs:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import requests
import time
import pandas as pd
def get_pubmed_results_count(search_terms, delay=1):
base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
results = {}
for term in search_terms:
# Define parameters for the API request
params = {
"db": "pubmed",
"term": term,
"retmode": "json"
}
try:
# Make the request to the PubMed API
response = requests.get(base_url, params=params)
response.raise_for_status()
# Parse the response
data = response.json()
count = data['esearchresult']['count']
results[term] = count
except requests.exceptions.RequestException as e:
print(f"Error retrieving data for term '{term}': {e}")
results[term] = None
# Respectful delay between requests
time.sleep(delay)
return results
# Example usage
df_searchterms = pd.read_csv('search1.csv')
print(df_searchterms)
if __name__ == "__main__":
#for index, row in df_searchterms.iterrows():
#search_terms = (row['Term'])
search_terms = ["APOE AND Alzheimer's"]
result_counts = get_pubmed_results_count(search_terms)
for term, count in result_counts.items():
df_results = pd.DataFrame(result_counts.items(), columns=['term', 'count'])
print (df_results)
df_results.to_csv('TestRestults1.csv', index=False)
</code>
<code>import requests import time import pandas as pd def get_pubmed_results_count(search_terms, delay=1): base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" results = {} for term in search_terms: # Define parameters for the API request params = { "db": "pubmed", "term": term, "retmode": "json" } try: # Make the request to the PubMed API response = requests.get(base_url, params=params) response.raise_for_status() # Parse the response data = response.json() count = data['esearchresult']['count'] results[term] = count except requests.exceptions.RequestException as e: print(f"Error retrieving data for term '{term}': {e}") results[term] = None # Respectful delay between requests time.sleep(delay) return results # Example usage df_searchterms = pd.read_csv('search1.csv') print(df_searchterms) if __name__ == "__main__": #for index, row in df_searchterms.iterrows(): #search_terms = (row['Term']) search_terms = ["APOE AND Alzheimer's"] result_counts = get_pubmed_results_count(search_terms) for term, count in result_counts.items(): df_results = pd.DataFrame(result_counts.items(), columns=['term', 'count']) print (df_results) df_results.to_csv('TestRestults1.csv', index=False) </code>
import requests
import time
import pandas as pd

def get_pubmed_results_count(search_terms, delay=1):
    base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
    results = {}

    for term in search_terms:
        # Define parameters for the API request
        params = {
            "db": "pubmed",
            "term": term,
            "retmode": "json"
        }

        try:
            # Make the request to the PubMed API
            response = requests.get(base_url, params=params)
            response.raise_for_status()

            # Parse the response
            data = response.json()
            count = data['esearchresult']['count']
            results[term] = count

        except requests.exceptions.RequestException as e:
            print(f"Error retrieving data for term '{term}': {e}")
            results[term] = None

        # Respectful delay between requests
        time.sleep(delay)

    return results

# Example usage

df_searchterms = pd.read_csv('search1.csv')
print(df_searchterms)

if __name__ == "__main__":
    #for index, row in df_searchterms.iterrows():
        #search_terms = (row['Term']) 
    search_terms = ["APOE AND Alzheimer's"]
    result_counts = get_pubmed_results_count(search_terms)
    
    for term, count in result_counts.items():
       df_results = pd.DataFrame(result_counts.items(), columns=['term', 'count'])
       print (df_results)
       df_results.to_csv('TestRestults1.csv', index=False)

And here is what my search terms data frame looks like:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> Term
0 APOE AND Alzheimer's
1 PSEN1 AND Alzheimer's
2 PSEN2 AND Alzheimer's
3 APP AND Alzheimer's
4 CLU AND Alzheimer's
</code>
<code> Term 0 APOE AND Alzheimer's 1 PSEN1 AND Alzheimer's 2 PSEN2 AND Alzheimer's 3 APP AND Alzheimer's 4 CLU AND Alzheimer's </code>
 Term
0   APOE AND Alzheimer's
1  PSEN1 AND Alzheimer's
2  PSEN2 AND Alzheimer's
3    APP AND Alzheimer's
4    CLU AND Alzheimer's

So my question is, can someone help me figure out where to put the for loop and how to replace the line:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>search_terms = ["APOE AND Alzheimer's"]
</code>
<code>search_terms = ["APOE AND Alzheimer's"] </code>
search_terms = ["APOE AND Alzheimer's"]

with the appropriate line that will instead run through the CSV file? Of note, if I comment out the current search_terms line and correctly tab the replacement line (currently commented out), then I get a “Key Error” for ‘count’. Please help, thank you in advance!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật