python – Difference between map and dict

python – Difference between map and dict

Map is not a datatype in python. It applies a function to a series of values and returns the result.

>>> def f(x):
...     return x**2
... 
>>> list(map(f, range(5)))
[0, 1, 4, 9, 16]

Often for a simple case like that to be pythonic we use list comprehensions.

>>> [x**2 for x in range(5)]
[0, 1, 4, 9, 16]

You are right in your comparison of hashmaps and dicts.

In essence a Map in Java is like a dict in Python: both data structures create associations between keys and values, with expected O(1) performance for the get() and contains() operations.

The Map data structure in Java should not be confused with the map() function in Python:

map(function, iterable, …)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel

python – Difference between map and dict

Nolens answer is for Python 2.

In Python 3, map is an iterable datatype, equivalent to what is returned by itertoolss imap in Python 2.

To get the same result as the first Python 2 example above in Python 3, you would write:

>>> def f(x):
...     return x**2
... 
>>> list(map(f, range(5)))

[0, 1, 4, 9, 16]

Leave a Reply

Your email address will not be published. Required fields are marked *