Home > Net >  how to write map, filter and spread in python3?
how to write map, filter and spread in python3?

Time:08-05

I am new to coding and trying to work on a code migration from JS to Python3. Please correct me wherever I am going wrong in conveying my question.

Here is my question

I have a js code where the function is written which finds the minimum of a particular value in the JSON file. Below is the code

 var jsonarray = data["data"]["result"]

                function findMinimum(data, key) {

                    // `filter` out the objects where the value of `cloud` matches your query
                    const result = data.data.result.filter(obj => {
                        return obj.metric.cloud?.toLowerCase() === key.toLowerCase();
                        // console.log(result)
                        // For each object return the second element of the value array
                    }).map(obj => {
                        return obj.value[1];
                    });

                    // `spread` out the array and use `Math.min` to find the minimum value
                    return Math.min(...result);
                }

                const clouds = data.data.result.map(obj => {
                    return obj.metric.cloud;
                    // console.log("test"   obj.metric.cloud)
                });

                // console.log(...new Set(clouds));
                arry = []
                arry.push(...new Set(clouds))

A detailed explanation of the JSON file and what this code is doing can be found here in my question https://stackoverflow.com/questions/72514765/how-to-find-particular-value-in-json-and-display-the-minimum-of-those-values-in]

I am trying to write this code in python3 but getting stuck while writing the filter function and spread function. Not able to set up correct syntax and merge as this function in JS. Below is the python code I tried which has many syntax errors and not working.

def findMinimum(data, key) {

                        result = data.data.result.filter(obj -> {
                        return obj.metric.cloud?.toLowerCase() === key.toLowerCase();
                       }).map(obj -> {
                       return obj.value[1];
                    });

                   return Math.min(...result);
                }

                clouds = data.data.result.map(obj -> {
                    return obj.metric.cloud;
                   });

              
                arry = []
                arry.append(...new Set(clouds))

Can anyone help me with this code converting or any source where I can read and understand easily about these functions in python which might be beginner-friendly?

CodePudding user response:

Okay, lemme just state that python syntax is different from JS. That said the functionality is quite the same barring the data structures used in them.

Converting, mapping and filtering:


Steps to do the above task, as best i can comprehend.

  1. Convert JSON to a python iterable or sequence. some info here
json_data_dict = json.loads(data.data.result)
  1. Filter the data. filter(filter_func, seq) is an inbuilt function that lets filter a sequence.
filtered_iter = filter(func_name, json_data_dict)
  1. Map the data. writes similar to filter map(map_func, seq)
mapped_iter = map(func_name, iterable)

if you are looking for chaining, functools may have some help for you. Otherwise you can compose them

filtered_then_mapped = map(map_func, filter(func_name, iterable));

more info here

Spread operator:


There is no special spread operator in python, you can just destructure lists and tuples in python like
x, y = (10, 20);
# or
my_tupl = (10, 20);
x, y = my_tuple;

the rest operator may be used like such

start, num_2, *end_nums = [0, 1, 2, 3, 4, 5]
print(start) # 0
print(num_2) # 1
print(end_nums) # [2, 3, 4, 5]

objects will be destructured using itemgetter and attrgetter from operator module

  • Related