Difference between map and dict
Solution 1
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.
Solution 2
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
Solution 3
Nolen's answer is for Python 2.
In Python 3, map is an iterable datatype, equivalent to what is returned by itertools's 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]
Solution 4
In Python 3, map returns an iteratable datatype, equivalent to what is returned by itertools's imap in Python 2.
To get the same results in Python 3 as Nolan Royalty's Python 2 example you would write:
>>> def f(x):
... return x**2
...
>>> list(map(f, range(5)))
[0, 1, 4, 9, 16]
If you don't wrap it in a list in Python 3, you will get a map object:
>>> map(f, range(5))
... <map object at 0x000000000327E780>
So there are map objects, which are iterable, in Python 3.
Solution 5
There is no map data type in python. map is a function that maps a function to an sequence.
def increment(n):
return n+1
l = [1,2,3]
map(increment, l)
will give you a new list [2,3,4]
frazman
Updated on June 29, 2020Comments
-
frazman almost 4 years
I might be confused between
hashmap
in Java, andmap
/dict
in Python.
I thought that thehash
(k/v abstraction) of Java is kind of the same asdict
in PythonBut then what does the
map
datatype do?Is it the same abstraction as the hashmap abstraction? If so, then how is it different from dictionary?
I went through the docs, but it took me to whole together different paradigm: functional programming. -
Maksym Polshcha about 12 yearsYeah, map isn't a datatype :-) See docs.python.org/library/functions.html#map
-
Nolen Royalty about 12 years@MaksymPolshcha thanks for the link, I've edited it into my post.
-
agf about 12 years"Guaranteed O(1) performance" isn't quite right. See wiki.python.org/moin/TimeComplexity
-
Josiah Yoder almost 7 yearsAs of Python 3, map is a datatype -- see my answer.
-
Josiah Yoder almost 6 yearsSee my update for Python 3, which was rejected as an edit.
-
Nolen Royalty almost 6 yearsThanks @JosiahYoder, I've updated my answer to wrap the
map
call withlist