Hash Map in Python

后端 未结 9 1049
礼貌的吻别
礼貌的吻别 2020-11-27 10:59

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 k

相关标签:
9条回答
  • 2020-11-27 11:25

    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" 
    
    0 讨论(0)
  • 2020-11-27 11:29
    class HashMap:
        def __init__(self):
            self.size = 64
            self.map = [None] * self.size
    
        def _get_hash(self, key):
            hash = 0
    
            for char in str(key):
                hash += ord(char)
            return hash % self.size
    
        def add(self, key, value):
            key_hash = self._get_hash(key)
            key_value = [key, value]
    
            if self.map[key_hash] is None:
                self.map[key_hash] = list([key_value])
                return True
            else:
                for pair in self.map[key_hash]:
                    if pair[0] == key:
                        pair[1] = value
                        return True
                    else:
                        self.map[key_hash].append(list([key_value]))
                        return True
    
        def get(self, key):
            key_hash = self._get_hash(key)
            if self.map[key_hash] is not None:
                for pair in self.map[key_hash]: 
                    if pair[0] == key:
                        return pair[1]
            return None
    
        def delete(self, key):
            key_hash = self._get_hash(key)
    
            if self.map[key_hash] is None :
                return False
            for i in range(0, len(self.map[key_hash])):
                if self.map[key_hash][i][0] == key:
                    self.map[key_hash].pop(i)
                    return True
    
        def print(self):
    
            print('---Phonebook---')
            for item in self.map:
                if item is not None:
                    print(str(item))
    
    h = HashMap()
    
    0 讨论(0)
  • 2020-11-27 11:33

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

    0 讨论(0)
提交回复
热议问题