def query4(transaction, **params):
    """
    Which 3 countries in the network have the most people within a specified age range?
    """
    query = f'''
        match $person isa person,
          has age > {params['age_lower']}, has age < {params['age_upper']};
        $country isa country, has name $country-name;
        (contains-city: $country, in-country: $city) isa has-city;
        (contains-residence: $city, in-city: $person) isa has-residence;
        get; group $country-name; count;
    '''
    print(f"\nQuery 4:\n {query}")
    iterator = transaction.query(query)
    result = []

    for item in list(iterator):  # Consume ResponseIterator into a list
        counts = item.answers()[0].number()
        country = item.owner().value()
        result.append({'country': country, 'personCounts': counts})

    sorted_results = sorted(result, key=lambda x: x['personCounts'], reverse=True)
    print(f"3 Countries with the most people with age > {params['age_lower']} and < {params['age_upper']}:  \
          \n{sorted_results[:3]}")
    return sorted_results