Home > Back-end >  Map Multiple Values to Python Dictionary Key from Two Different Lists
Map Multiple Values to Python Dictionary Key from Two Different Lists

Time:04-14

I have a user list userList = [Bob, Sam, Sue, Jen]

Each user has specific permissions that return from passing their name into another function. For example, Bob has read access, while every one else has read and write access.

When I pass Bob's name into my permission function, the result returns a list with his permission, Ex: permission('Bob') returns: ['Read']

While permission('Sue') returns: ['Read', 'Write']

What is the best way to create a dictionary that takes each name as a key and maps each permission as a list of values for that key. Output expected would be {'Bob':['Read'], 'Sam':['Read', 'Write'], 'Sue':['Read', 'Write'], 'Jen':['Read', 'Write']}

I'm thinking something like:

d = {}
for i in userList:
      permissions = permission(i)

This is all I have so far so was hoping someone might have a = solution or something. Any help would be greatly appreciated.

CodePudding user response:

Just wanna elaborate on my comment with an example, which hopefully illuminates the usage:

names = ["bob", "sarah", "john"]

def get_length_squared(name):
    return len(name) ** 2

mapping = dict(zip(names, map(get_length_squared, names)))

for key, value in mapping.items():
    print(f"{key}: {value}")

Output:

bob: 9
sarah: 25
john: 16
>>> 
  • Related