From 7f9c9b7062786e450358a3e3150688becb731110 Mon Sep 17 00:00:00 2001 From: AlanPCS Date: Wed, 21 Oct 2020 21:49:25 -0300 Subject: [PATCH] Add pluck --- snippets/pluck.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/pluck.md diff --git a/snippets/pluck.md b/snippets/pluck.md new file mode 100644 index 000000000..05d7121f1 --- /dev/null +++ b/snippets/pluck.md @@ -0,0 +1,25 @@ +--- +title: pluck +tags: list,dictionary,intemediary +--- + +Extracts a list of values from a dict given a key + +- Given an `array` of `dict`s, returns the list of values of the `key` passed from each dict record. +- When a dict does not have the `key` passed, returns `None` + +```py +def pluck(array, key): + return list(map(lambda entry: dict.get(entry, key), array)) +``` + +```py +simpsons = [ + { "name": "lisa", "age": 8 }, + { "name": "homer", "age": 36 }, + { "name": "marge", "age": 34 }, + { "name": "bart", "age": 10 }, +]; + +pluck(simpsons, "age") # [8, 36, 34, 10] +``` \ No newline at end of file