How to extract one of multiple matching values from list with priority?

Viewed 56

I have a list of dictionaries

list_ = [
    {'id': '1', 'name': 'ABC', 'email': 'abc@gmail.com', 'role': 'Tester'},
    {'id': '2', 'name': 'CDE', 'email': 'cde@gmail.com', 'role': 'Developer'},
    {'id': '3', 'name': 'fgh', 'email': 'fgh@gmail.com', 'role': 'Developer'},
    {'id': '2', 'name': 'CDE', 'email': 'cde@gmail.com', 'role': 'Tester'},
    {'id': '1', 'name': 'ABC', 'email': 'abc@gmail.com', 'role': 'Developer'}
]

I am trying to extract a particular role from the list which matches the key.

Developer has higher priority than Tester. If for a particular ID both Developer and Tester is present then the output should be Developer.

However, if the list has Tester coming first, then my code won't work, it will give Tester instead of Developer.

How can I do this correctly? Do I need to put a break statement?

def find_role(id_, list_):
    role = 'user'
    for each in list_:
        if id_ == each['id'] and each['role'] == 'Developer':
            role = 'Developer'
            return role
        if id_ == each['id'] and each['role'] == 'Tester':
            role = 'Tester'
            return role
    return role
find_role('1', list_)
2 Answers

Your current script does not assess role priority. Instead it returns the first role from your selected set.

def find_role(id_, list_):
    role = 'user'
    for each in list_:
        if id_ == each['id']:
            # check for first role priority
            if each['role'] == 'Developer':
                role = 'Developer'
            # if first role priority has not been assigned, check for next
            elif role != 'Developer' and each['role'] == 'Tester':
                role = 'Tester'
    return role
find_role('1', list_)

You can search for 'Tester' firstly until you find 'Developer' role. When you find it you can return that value

def find_role(id_, list_):
    role = 'User'
    for each in list_:
        if id_ == each['id'] and each['role'] == 'Tester':
            role= 'Tester'
        if id_ == each['id'] and each['role'] == 'Developer':
                role = 'Developer'
                return role
    return role
Related