Files
30-seconds-of-code/snippets/map_object.md
Angelos Chalaris 82d99f98cb Apply suggestions from code review
Co-Authored-By: Isabelle Viktoria Maciohsek <maciv@hotmail.gr>
2020-03-16 22:00:46 +02:00

22 lines
533 B
Markdown

---
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 original value as the key and the result of the function as the 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 }
```