I am struggling to write a lambda function for a pandas column (list of dictionaries of movie crew members) with a loop and if-statement. The function returns the value of the key name
for the dictionary in the list that also has a value of 'Director'
for the key job
. I am wondering if there is a way to convert my working director
function to lambda. I can just do df.apply(director)
but curious on how it can be done with lambda.
Code and examples below:
# This is the regular working function. x is a list of dictionaries.
def director(x):
for i in x:
if i['job'] == 'Director':
return i['name']
return ''
# My lambda attempt that would work but some rows may be empty
df.apply(lambda x: [i['name'] for i in x if i['job'] == 'Director'][0])
Solved with:
df.apply(lambda x: next((i['name'] for i in x if i['job'] == 'Director'), ''))