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.

Asked By: UneRoue

||

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.

Answered By: Cstack2

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()
Answered By: Swifty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.