The Python Oracle

Hash Map in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC E Schuberts Piano Sonata D 784 in A

--

Chapters
00:00 Question
00:37 Accepted answer (Score 345)
01:25 Answer 2 (Score 36)
01:42 Answer 3 (Score 32)
02:22 Answer 4 (Score 20)
02:52 Thank you

--

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

Accepted answer links:
[Python dictionary]: http://docs.python.org/library/stdtypes....

Answer 2 links:
[dictionaries]: http://docs.python.org/tutorial/datastru...

Answer 3 links:
[dictionaries]: http://docs.python.org/tutorial/datastru...

Answer 4 links:
[dictionaries]: http://docs.python.org/tutorial/datastru...

--

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