pythonjsondictionary-comprehension

Understanding comprehension sets


I have this code:

class ApiCall(object):

    def __init__(self, url):
        self.url = url

    def call(self):
        call = requests.get(self.url)
        response = call.content.decode('utf-8')
        result = json.loads(response)
        return result


class IncomeSources(object):

    def __init__(self, result):
        self.result = result

    def all(self):
            #This is the dict comprehension
            #return {(slot['accountLabelType'], slot['totalPrice']) for slot in self.result}

            for slot in self.result:

                return (slot['accountLabelType'], slot['totalPrice'])

def main():
            url = ('https://datafeed/api/')
            api_result = ApiCall(url).call()
            target = IncomeSources(api_result).all()
            print(target)


main()

The result with a regular for on a function, returns this which is not desired, as it only returns the pair of the first object:

('Transport', 888)

But with the dict comprehension, it returns all slot pairs of all the JSON objects on that JSON response (that is cool). Why does the dict comprehension grab all the pairs and the regular for does not?


Solution

  • Why the dict comprehension grabs all the pairs and the regular for is not ?

    What happens when you loop over something and have a return statement in the loop is that as soon as a return statement is encountered, that value (and only that value) is returned.

    The dict comprehension first constructs the entire dictionary which then gets returned as a whole to the caller.

    This has less to do with the comprehension and more with the return statement. Compare:

    >>> def foo():
    ...     for i in range(5):
    ...         return i
    ...
    >>> foo()
    0
    

    With:

    >>> def foo():
    ...     return list(range(5))
    ...
    >>> foo()
    [0, 1, 2, 3, 4]