The Python Oracle

Hash Map in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping

--

Chapters
00:00 Hash Map In Python
00:24 Accepted Answer Score 377
01:01 Answer 2 Score 24
01:26 Answer 3 Score 41
01:37 Answer 4 Score 34
01:58 Thank you

--

Full question
https://stackoverflow.com/questions/8703...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #hashmap

#avk47



ACCEPTED ANSWER

Score 377


Python dictionary is a built-in type that supports key-value pairs. It's the nearest builtin data structure relative to Java's HashMap.

You can declare a dict with key-value pairs set to values:

streetno = {
    "1": "Sachin Tendulkar",
    "2": "Dravid",
    "3": "Sehwag",
    "4": "Laxman",
    "5": "Kohli"
}

You can also set a key-value mapping after creation:

streetno = {}
streetno["1"] = "Sachin Tendulkar"
print(streetno["1"]) # => "Sachin Tendulkar"

Another way to create a dictionary is with the dict() builtin function, but this only works when your keys are valid identifiers:

streetno = dict(one="Sachin Tendulkar", two="Dravid")
print(streetno["one"]) # => "Sachin Tendulkar"



ANSWER 2

Score 41


All you wanted (at the time the question was originally asked) was a hint. Here's a hint: In Python, you can use dictionaries.




ANSWER 3

Score 34


It's built-in for Python. See dictionaries.

Based on your example:

streetno = {"1": "Sachine Tendulkar",
            "2": "Dravid",
            "3": "Sehwag",
            "4": "Laxman",
            "5": "Kohli" }

You could then access it like so:

sachine = streetno["1"]

Also worth mentioning: it can use any non-mutable data type as a key. That is, it can use a tuple, boolean, or string as a key.




ANSWER 4

Score 24


Hash maps are built-in in Python, they're called dictionaries:

streetno = {}                        #create a dictionary called streetno
streetno["1"] = "Sachin Tendulkar"   #assign value to key "1"

Usage:

"1" in streetno                      #check if key "1" is in streetno
streetno["1"]                        #get the value from key "1"

See the documentation for more information, e.g. built-in methods and so on. They're great, and very common in Python programs (unsurprisingly).