Value is printing twice rather than once
Question:
I have this code. The count of values from the first url always displays twice. But the sum is right.
So I get
4
4
2
6
Instead of
4
2
6
def count_blocklist_entries():
urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt']
entry_dict = {}
for url in urls:
response = requests.get(url)
lengthers = len(response.text.splitlines())
entry_dict.update({url: lengthers})
print(lengthers)
print(sum(entry_dict.values()))
count_blocklist_entries()
Expecting to not get the first integer twice.
Answers:
This is what is occurring within the entry_dict variable:
Iteration 1: {'https://rad.net/Easylist.txt': 4}
Sum of values in dictionary = 4
Iteration2: {'https://rad.net/Easylist.txt': 4, 'https://rad.net/Admiral.txt': 2}
Sum of values in dictionary = 6
If you wanted to only print out the sum(entry_dict.values())
after adding all the urls to the entry_dict dictionary, that line should be added outside the for loop.
Simply move the sum printing to the actual end of the code, after the "for" loop:
def count_blocklist_entries():
urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt']
entry_dict = {}
for url in urls:
response = requests.get(url)
lengthers = len(response.text.splitlines())
entry_dict.update({url: lengthers})
print(lengthers)
print(sum(entry_dict.values()))
count_blocklist_entries()
I have this code. The count of values from the first url always displays twice. But the sum is right.
So I get
4
4
2
6
Instead of
4
2
6
def count_blocklist_entries():
urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt']
entry_dict = {}
for url in urls:
response = requests.get(url)
lengthers = len(response.text.splitlines())
entry_dict.update({url: lengthers})
print(lengthers)
print(sum(entry_dict.values()))
count_blocklist_entries()
Expecting to not get the first integer twice.
This is what is occurring within the entry_dict variable:
Iteration 1: {'https://rad.net/Easylist.txt': 4}
Sum of values in dictionary = 4
Iteration2: {'https://rad.net/Easylist.txt': 4, 'https://rad.net/Admiral.txt': 2}
Sum of values in dictionary = 6
If you wanted to only print out the sum(entry_dict.values())
after adding all the urls to the entry_dict dictionary, that line should be added outside the for loop.
Simply move the sum printing to the actual end of the code, after the "for" loop:
def count_blocklist_entries():
urls = ['https://rad.net/Easylist.txt', 'https://rad.net/Admiral.txt']
entry_dict = {}
for url in urls:
response = requests.get(url)
lengthers = len(response.text.splitlines())
entry_dict.update({url: lengthers})
print(lengthers)
print(sum(entry_dict.values()))
count_blocklist_entries()