0

I have a dictionary that associates people to their skills:

d = {
    'A': {'name': 'Peter', 'skill': 'python'},
    'B': {'name': 'Mary', 'skill': 'c#'},
    'C': {'name': 'James', 'skill': 'java'}
 }

I have a list that specified required skills for different assignments:

e = [
    ['python', 'java'],
    ['c#', 'R']
]

I need to generate a new list with name of people that have the skill requested (or 'N/A' if none found). In this case, the result will be:

rslt= [['Peter', 'James'], ['Mary', 'N/A']]

The following for-loop(s) generate the result.

# with for loops
for r in range(len(e)):
    for s in range(0,len(e[r])):
        skill_found = 'false'
        for k in d.keys():
            if e[r][s] == d[k]['skill']:
                rslt[r][s] = d[k]['name']
                skill_found = 'true'
                break
        if skill_found == 'false':
                rslt[r][s] = 'N/A'
print(rslt)

However, I'd really like to obtain some list/dictionary comprehension to do the same, which I've consistently failed at. The following two statements generate garbage:

#with list/dict comprehension
lstComp1 = [[d[k]['name'] if str(e[y][x]) == d[k]['skill'] else 'N/A' for x in range(0, len(e[y])) for k in d.keys()] for y in range(len(e))]
lstComp2 = [[x if x in d else 'N/A' for x in range(len(e[y]))] for y in range(len(e))]
print( lstComp1)
print(lstComp2)

Any help would be most appreciated.

2
  • Can be in dictionary d multiple people with same skill? Do you want only chose one person at random with required skill? May 4, 2020 at 18:10
  • In the application I'm planning, the skill attribute will be unique (or one per person). But a more general solution (e.g., different people with same skills) one selected at random as you suggest will be interesting to have as well.
    – ajbg
    May 4, 2020 at 18:14

2 Answers 2

2

If you use Python 3.8, you could transform the for-loop into one-liner:

d = {
    'A': {'name': 'Peter', 'skill': 'python'},
    'B': {'name': 'Mary', 'skill': 'c#'},
    'C': {'name': 'James', 'skill': 'java'}
}

e = [
    ['python', 'java'],
    ['c#', 'R']
]

rslt = [[person['name'] if any((person:=v)['skill']==skill for v in d.values()) else 'N/A' for skill in task] for task in e]

print(rslt)

Prints:

[['Peter', 'James'], ['Mary', 'N/A']]
2

@andrej's answer is good. I have written this for any python3.x

_any is just an imitation of any but here it returns a dictionary to make things easier.

def _any(d,val):
    for v in d.values():
        if v['skill']==val:
            return v
    return {'name':'N/A'}
[[_any(d,v)['name'] for v in lst] for lst in e]
# [['Peter', 'James'], ['Mary', 'N/A']]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.