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.
d
multiple people with same skill? Do you want only chose one person at random with required skill?