frazman
frazman

Reputation: 33243

Difference between map and dict

I might be confused between hashmap in Java, and map/dict in Python.
I thought that the hash (k/v abstraction) of Java is kind of the same as dict in Python

But 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.

Upvotes: 48

Views: 49841

Answers (4)

Josiah Yoder
Josiah Yoder

Reputation: 3756

Yes, dict is the Python equivalent of the Java Map, HashMap, TreeMap, etc.

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.

Upvotes: 5

Nolen Royalty
Nolen Royalty

Reputation: 18633

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.

Upvotes: 49

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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

Upvotes: 8

DiamRem
DiamRem

Reputation: 612

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]

Upvotes: 3

Related Questions