<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def get_applied_migrations(databases=None):
 """ Returns a dictionary containing lists of all applied migrations where the key is the database alias. """

    if not databases:
        databases = get_capable_databases()
    else:
        # We only loop through databases that are listed as "capable"
        all_databases = list(get_capable_databases())
        databases = list(
            itertools.ifilter(lambda x: x in all_databases, databases)
        )
    
    results = defaultdict(list)
    for db in databases:
        for x in Migration.objects.using(db).order_by("migration_label"):
            results[db].append(x.migration_label)
    
    return results