Yes, of course, same as with the parameters to any function. Arguments are only bound to the functionās parameters when the function is called, not when it is defined, and the names inside and outside a function resides in separate scopesāthatās the whole power of functions to begin with,
The user does so in their OP, and I do so here:
lambda v: {
"open_time": float(v[0]),
"open": float(v[1]),
"high": float(v[2]),
"low": float(v[3]),
"close": float(v[4]),
}
This is perfectly valid code; the lambda function is defined without any need to āpre-defineā a variable v
, as indeed the parameter v
inside the function is independent of any variable that might happen to be named v
with the same name outside of it.
If I wanted to do something more useful, simply consider the minimally fixed version of the OPās example:
def convert_lists_to_dicts(data):
return list(
map(
lambda v: {
"open_time": float(v[0]),
"open": float(v[1]),
"high": float(v[2]),
"low": float(v[3]),
"close": float(v[4]),
},
data,
)
)
Thereās no v
(or data
) hardcoded here. map_data_to_dict
could then be called with data
at any later point like so:
convert_lists_to_dicts([(1, 2, 3, 4, 5), (6, 7, 8, 9, 10)])
Of course, as @jeff5 and I illustrate, this function could be written more concisely and elegantly a number of ways without needing a lambda
, e.g.
FIELDS = ["open_time", "open", "high", "low", "close"]
def convert_lists_to_dicts(data):
return [dict(zip(FIELDS, map(float, v))) for v in data]