[Python] Understanding comprehension sets

Discussão em 'Python' iniciado por Stack, Julho 24, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página