Home > Mobile >  Lambda function in Python using dictionaries
Lambda function in Python using dictionaries

Time:02-15

I need to convert two functions into lambda versions of the same function, I'll post the code and my attempt that isn't working. This is using dictionaries in Python and mapping pairs and then reducing them. For the actual assignment I'm counting odds/evens and these are mapped to either a 1 or 0 but here I'm just using random numbers. I believe without the errors this is minimum replicable code. Thanks for the help!

I attempted changing one line to this: mapping = lambda v,k: [(key,val) for key in evenOddDict.items()]

Because it didn't recognize key/val. I'm not sure if something special needs to be done for dictionaries here.

#mapping function without lambda
#def mapping(key,val):
#    reverse = (val,key)
#    return reverse

#mapping function with lambda
mapping = lambda v,k: [(key,val) for entry in dummydata.items()]

#mapReduce function without lambda
#def mapReduce(key,val):
#    if key not in final_output:
#        final_output[key] = []
#    final_output[key].append(val)

#mapReduce function with lambda
mapReduce = lambda k,v:final_output[k]   v

dummydata = {11:1, 36:0, 53:1, 77:0, 95:1, 22:0, 40:1, 63:0, 85:1, 17:0}

map_output = []
for k,v in dummydata.items():
    tmp = mapping(k,v)
    map_output.append(tmp)
    
for k, v in map_output:
    mapReduce(k,v)

print("\n\n====================================================")
print("       After mapReduce and Final Output")
print("====================================================\n\n")

for i in range (len(map_output)):
    print(map_output[i])

print("\n\n")

for key in final_output:
    print (key,final_output[key])

print("\n\n")

CodePudding user response:

These are equivalent versions of your two functions without lambdas.

mapping = lambda k, v: (v, k)

mapReduce = lambda k, v: final_output.setdefault(k, []).append(v)

I'll mention in passing that naming lambdas is apparently somewhat discouraged, and, according to PEP 8:

The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

If there's a reason you're doing this besides an assignment's requirement, that would be interesting to share, as the consensus seems to be that there is no benefit to named lambdas over normal functions (and some downsides, such as tracebacks for debugging).

  • Related