Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash Map in Python

Tags:

python

hashmap

I want to implement a HashMap in Python. I want to ask a user for an input. depending on his input I am retrieving some information from the HashMap. If the user enters a key of the HashMap, I would like to retrieve the corresponding value.

How do I implement this functionality in Python?

HashMap<String,String> streetno=new HashMap<String,String>();
   streetno.put("1", "Sachin Tendulkar");
   streetno.put("2", "Dravid");
   streetno.put("3","Sehwag");
   streetno.put("4","Laxman");
   streetno.put("5","Kohli")
like image 798
Kiran Bhat Avatar asked Jan 02 '12 17:01

Kiran Bhat


People also ask

What is a HashMap in Python?

Hash maps are a common data structure used to store key-value pairs for efficient retrieval. A value stored in a hash map is retrieved using the key under which it was stored. # `states` is a Hash Map with state abbreviation keys and state name values.

Is HashMap same as dictionary in Python?

In Python, dictionaries (or “dicts”, for short) are a central data structure: Dicts store an arbitrary number of objects, each identified by a unique dictionary key. Dictionaries are often also called maps, hashmaps, lookup tables, or associative arrays.

What is the use of HashMap?

HashMap is a data structure that uses a hash function to map identifying values, known as keys, to their associated values. It contains “key-value” pairs and allows retrieving value by key.

Is Python set a HashMap?

So basically a set uses a hashtable as its underlying data structure.


3 Answers

Python dictionary is a built-in type that supports key-value pairs.

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

as well as using the dict keyword:

streetno = dict({"1": "Sachin Tendulkar", "2": "Dravid"}) 

or:

streetno = {}
streetno["1"] = "Sachin Tendulkar" 
like image 66
Alan Avatar answered Oct 17 '22 21:10

Alan


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

like image 34
Christian Neverdal Avatar answered Oct 17 '22 22:10

Christian Neverdal


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.

like image 32
Edwin Avatar answered Oct 17 '22 20:10

Edwin