﻿ Python: Map dictionary - w3resource

# Python: Map dictionary

## Python dictionary: Exercise-70 with Solution

Write a Python program to map the values of a given 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 map() to apply fn to each value of the list.
• Use zip() to pair original values to the values produced by fn.
• Use dict() to return an appropriate dictionary.

Sample Solution:

Python Code:

``````# Define a function 'test' that takes two arguments: 'itr' (an iterable) and 'fn' (a function).
def test(itr, fn):
# Use the 'zip' function to pair each element from 'itr' with the result of applying 'fn' to that element.
# Convert the zipped pairs into a dictionary where the elements from 'itr' are keys, and the results of 'fn' are values.
return dict(zip(itr, map(fn, itr)))

# Call the 'test' function with an iterable [1, 2, 3, 4] and a lambda function that squares its input.
# The lambda function calculates the square of each element in the iterable.
result = test([1, 2, 3, 4], lambda x: x * x)

# Print the resulting dictionary.
print(result)
```
```

Sample Output:

```{1: 1, 2: 4, 3: 9, 4: 16}
```

Flowchart:

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿