From 3de4296dc8be2950e9310ecec9b64c421d0118ec Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 16 Mar 2020 19:51:03 +0200 Subject: [PATCH] Add map_object --- snippets/map_object.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/map_object.md diff --git a/snippets/map_object.md b/snippets/map_object.md new file mode 100644 index 000000000..5eebb5843 --- /dev/null +++ b/snippets/map_object.md @@ -0,0 +1,20 @@ +--- +title: map_object +tags: list,intermediate +--- + +Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the value as the key and the mapped value. + +Use a `for` loop to iterate over the list's values, assigning the values produced by `fn` to each key of the dictionary. + +```py +def map_object(itr, fn): + ret = {} + for x in itr: + ret[x] = fn(x) + return ret +``` + +```py +map_object([1,2,3], lambda x: x * x) # { 1: 1, 2: 4, 3: 9 } +```