0

I am mapping one array to another using a function called filter_json as such:

filtered_json = map(filter_json, data_json)

def filter_json(data_json):
    """Filter data_json to data that is needed"""
    ...
    # return mapped dictionary

Now I want to the filter_json function to accept another parameter. Something like this (but this obviously doesn't work):

filtered_json = map(filter_json, data_json, var)

def filter_json(data_json, var):
    """Filter data_json to data that is needed"""
    ... # do something with var
    # return mapped dictionary

How do I pass in more variables into filter_json?

etayluz
  • 15,920
  • 23
  • 106
  • 151

2 Answers2

3

Two potential approaches:

  1. use functools.partial

    import functools
    f = functools.partial(filter_json, var=var)
    filtered_json = map(f, data_json)
    
  2. ... or use a list comprehension instead of map:

    filtered_json = [ filter_json(x, var) for x in data_json ]
    

    If you want an lazily-evaluated iterator rather than a list, use round brackets instead of square brackets—then it's called a generator expression rather than a list comprehension.

I generally prefer option 2, on grounds of readability, and the flexibility to include if conditionals and nested loops in the iteration.

jez
  • 14,867
  • 5
  • 37
  • 64
2

You can use a lambda to call the function with the variable you want

filtered_json = map(lambda data: filter_json(data, var), data_json)

def filter_json(data_json, var):
    """Filter data_json to data that is needed"""
    ... # do something with var
    # return mapped dictionary
tdelaney
  • 73,364
  • 6
  • 83
  • 116