Python 7 - Dictionary Examples, get() vs. setdefault()

By Sheldon L Published at 2020-03-28 Updated at 2020-03-28


def groups_per_user(group_dictionary):
    user_groups = {}
    for group, users in group_dictionary.items():
        for user in users:
            user_groups.setdefault(user, []).append(group)         # setdefault()
    return(user_groups)

print(groups_per_user({
  "local": ["admin", "userA"],
  "public":  ["admin", "userB"],
  "administrator": ["admin"]
}))
# No Error
def groups_per_user(group_dictionary):
    user_groups = {}
    for group, users in group_dictionary.items():
        for user in users:
            user_group[user] = user_groups.get(user, []).append(group)  # get()
    return(user_groups)

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

# ERROR!
# Traceback (most recent call last):
#   File "test.py", line 11, in <module>
#     "administrator": ["admin"]
#   File "test.py", line 5, in groups_per_user
#     user_groups[user] = user_groups.get(user, []).append(group)
# AttributeError: 'NoneType' object has no attribute 'append'