как изменить в словарях? - PullRequest
0 голосов
/ 30 марта 2020

Функция groups_per_user получает словарь, который содержит имена групп со списком пользователей. Пользователи могут принадлежать к нескольким группам. Заполните пробелы, чтобы вернуть словарь с пользователями в качестве ключей и список их групп в качестве значений

def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary
    for ___:
        # Now go through the users in the group
        for ___:
            # Now add the group to the the list of
# groups for this user, creating the entry
# in the dictionary if necessary

    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))

Ответы [ 3 ]

1 голос
/ 30 марта 2020

Попробуйте это:

def groups_per_user(group_dictionary):
    user_groups = {}
    for grp, users in group_dictionary.items():
        for user in users:
            if user in user_groups:
                user_groups[user].append(grp)
            else:
                user_groups[user] = [grp]

    return (user_groups)

Вывод вашего print оператора:

{'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']}
1 голос
/ 30 марта 2020
def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary
    for group in group_dictionary:
        # Now go through the users in the group
        for user in group_dictionary[group]:
            try:
                user_groups[user].append(group)
            except KeyError:
                user_groups[user] = [group]
            # Now add the group to the the list of
# groups for this user, creating the entry
# in the dictionary if necessary

    return(user_groups)
0 голосов
/ 30 марта 2020
def groups_per_user(group_dictionary):
    user_groups = {}
    for group in group_dictionary:
        for user in group_dictionary[group]:
            if user not in user_groups:
                user_groups[user] = []
            if group not in user_groups[user]:
                user_groups[user].append(group)
    return user_groups

mylist = {"local": ["admin", "userA"],
          "public":  ["admin", "userB"],
          "administrator": ["admin"] }

print(groups_per_user(mylist))
# {'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']}

...