Hướng dẫn hashmap trong python

When it comes to programming language advantage , both java and python have their own strong points. One of the most useful feature offered by both Java and Python are the HashMap and Dictionary. The use cases for both of these are similar. Basically whenever we need a Key value pair to be stored , these data structures are used in their respective languages. Even though both of them seem to be doing the same function , this article explains how both of them differ internally.

Basic principle:

Java : It uses principle of hashing and internally uses hashcode as base for storing key value pairs. With the help of hashcode , HashMap distributes the objects across array buckets(similar objects grouped together) in such a way that HashMap puts the object and retrieves it in constant time O(1).

Python: It uses the principle of re sizable hashtable in the background. The keys given to dictionaries are objects which have an in built hash function. With help of hash function, the keys gets distributed evenly across an array. Assuming that you’re storing keys that all have different hash values, this means that dictionaries take constant time – O(1), in computer science notation – to retrieve a key.

HashCode:

Java : Hashcode is integer value that identifies the object and is built using object's hashcode() method.Every object has hashcode() method, when called, it returns integer value that represents object. Two different objects can have same identifier/hashcode, in that case, to uniquely identify an object, other properties of object is used. hashcode() method looks into object properties, manipulate on it and come up with specific integer value which represents that object. hashcode is basically used for distributing and arranging objects across hashmap table.

Python : In python hash values are integers used to quickly compare dictionary keys while looking up a dictionary.On creating a dictionary, is being called by it.The Python hash() function calls __hash__() method internally to operate on different types of data types. __hash__() method is set by default for any object. Only immutable objects can be hashed. So the Keys in the dictionary should be immutable(int, float, bool, string, unicode, tuple). In python two different objects may result in the same hash value. Eg: integer 2 and float 2.0. This is called as collision. Python doesn’t have a hash function which can manage this problem. 

Final Working:

Java : The hash code of the key is generated and this is used as index for storing this key in an inbuilt HashMap array. Hashcode method helps in distributing the objects into certain categories or buckets. Multiple objects can end up in same bucket but has been categorized and we have less objects to search now.Equals method comes into picture now .This helps us to look within the objects that have the same hashcodes and get the object we are interested in by comparing object internal properties. The hash code is used as an index for hashmap internal array we retrieve corresponding value of the key. In case the keys get in the same bucket ,a linked list will be created for this hash index and the values of the respective keys are stored here .

Python : A good hash function minimizes the number of collisions e.g. different keys having the same hash. Python does not have this kind of hash function. So it uses a different methodology for using the hashcode as index of the inbuilt array. If an array of size x is used to store the key/value pairs then we use a mask equal to x-1 to calculate the slot index of the pair in the array. This makes the computation of the slot index fast. If still a collision exist , it does not create a linked list as it would increase the lookup time. So for this problem python uses Open Addressing. Open addressing is a method of collision resolution where probing is used. In case we had two keys having same hashcode,the first one has already occupied a slot in the array ,it probes for the next free index for the second key with the same hashcode. Adding a key/value pair will average O(1) and the lookup operation too.

So these are the differences between the two data structures in java and python .Both are useful for different business solution. Making the best use of the programming language is ultimately left to the user.

Mục lục

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người.
Là một website được viết trên công nghệ web Flutter vì vậy hỗ trợ rất tốt cho người học, kể cả những người học khó tính nhất.
Hiện tại website đang tiếp tục được cập nhập nội dung cho phong phú và đầy đủ hơn. Mong các bạn nghé thăm và ủng hộ website mới của chúng tôi. Hãy theo dõi chúng tôi trên Fanpage để nhận được thông báo mỗi khi có bài viết mới. Facebook

1- Python Dictionary

Trong Python, dictionary (bộ từ điển) là một kiểu dữ liệu, nó là một danh sách các phần tử (element), mà mỗi phần tử là một cặp khóa và giá trị (Key & value), nó khá giống với khái niệm Map trong Java.

Các dictionary đều là là đối tượng của lớp dict.

Để viết một dictionary sử dụng cặp dấu móc { } , và viết các phần tử bên trong, các phần tử phân cách nhau bởi đấu phẩy. Mỗi phần tử là một cặp khóa và giá trị ngăn cách nhau bởi dấu hai chấm ( : )

Ví dụ:


# Dictionary

myinfo =  {"Name": "Tran", "Age": 37, "Address" : "Vietnam"  }

Bạn cũng có thể tạo một đối tượng dictionary từ phương thức khởi tạo (constructor) của lớp dict.

createDictionaryFromClass.py


# Tạo một dictionary thông qua constructor của lớp dict.
mydict = dict()

mydict["E01"] =  "John"
mydict["E02"] =  "King"

print ("mydict: ", mydict)

Output:


mydict: {'E01': 'John', 'E02': 'King'}

Đặc điểm của giá trị (value) trong dictionary:

  • Mỗi phần tử (element) của dictionary là một cặp (khóa và giá trị), giá trị có thể là một kiểu bất kỳ (string, số, các kiểu người dùng tự định nghĩa,....), và cho phép trùng lặp.

Đặc điểm của khóa (key) trong dictionary.

  • Khóa trong dictionary phải là kiểu bất biến (immutable). Như vậy nó có thể là string, số, Tuple, ....
  • Một số kiểu không được phép, chẳng hạn List (Danh sách), vì List là kiểu dữ liệu biến đổi (mutable).
  • Các khóa trong dictionary không được phép trùng lặp.

Ví dụ:

dictionaryExample.py


# Dictionary
myinfo =  {"Name": "Tran", "Age": 37, "Address" : "Vietnam"  }

print ("myinfo['Name'] = ", myinfo["Name"])
print ("myinfo['Age'] = ", myinfo["Age"]) 
print ("myinfo['Address'] = ", myinfo["Address"])

Output:


myinfo['Name'] = Tran
myinfo['Age'] = 37
myinfo['Address'] = Vietnam

2- Cập nhập Dictionary

Dictionary cho phép cập nhập giá trị ứng với một khóa nào đó, nó thêm mới một phần tử nếu khóa đó không tồn tại trên dictionary.

updateDictionaryExample.py


# Dictionary 
myinfo =  {"Name": "Tran", "Age": 37, "Address" : "Vietnam"  }

# Cập nhập giá trị cho khóa (key) 'Address'
myinfo["Address"] = "HCM Vietnam"

# Thêm một phần tử mới với khóa (key) là 'Phone'.
myinfo["Phone"] = "12345" 

print ("Element count: ", len(myinfo) ) 
print ("myinfo['Name'] = ", myinfo["Name"]) 
print ("myinfo['Age'] = ", myinfo["Age"]) 
print ("myinfo['Address'] = ", myinfo["Address"]) 
print ("myinfo['Phone'] = ", myinfo["Phone"])

Output:


Element count: 4
myinfo['Name'] = Tran
myinfo['Age'] = 37
myinfo['Address'] = HCM Vietnam
myinfo['Phone'] = 12345

3- Xóa dictionary

Có 2 cách để loại bỏ một phần tử ra khỏi một dictionary.

  1. Sử dụng toán tử del
  2. Sử dụng phương thức __delitem__(key)

deleteDictionaryExample.py


# (Key,Value) = (Tên, Số điện thoại)
contacts = {"John": "01217000111", \
            "Tom": "01234000111", \
            "Addison":"01217000222", "Jack":"01227000123"}

print ("Contacts: ", contacts)
print ("\n")
print ("Delete key = 'John' ")

# Xóa một phần tử ứng với khóa 'John'
del contacts["John"]  
print ("Contacts (After delete): ", contacts) 
print ("\n")
print ("Delete key = 'Tom' ")

# Xóa một phần tử ứng với khóa 'Tom'
contacts.__delitem__( "Tom")  
print ("Contacts (After delete): ", contacts)  
print ("Clear all element")

# Xóa toàn bộ các phần tử.
contacts.clear() 
print ("Contacts (After clear): ", contacts)

# Xóa luôn dictionary 'contacts' khỏi bộ nhớ 
del contacts 
# Lỗi xẩy ra khi truy cập vào biến không tồn tại trên bộ nhớ
print ("Contacts (After delete): ", contacts)

4- Các hàm với với Dictionary

HàmMô tả
len(dict)

Trả về số phần tử của dict.

str(dict)

Hàm chuyển đổi ra một string biểu diễn dictionary.

type(variable)

Trả về kiểu của biến được truyền vào. Nếu biến truyền vào là một dictionary, thì nó sẽ trả về đối tượng đại diện lớp 'dict'.

dir(clazzOrObject) Trả về danh sách các thành viên của lớp (hoặc đối tượng) được truyền vào. Nếu truyền vào là lớp dict, nó sẽ trả về danh sách các thành viên của lớp dict.

functionDictionaryExample.py


contacts = {"John": "01217000111" ,"Addison": "01217000222","Jack": "01227000123"} 
print ("contacts: ", contacts)  
print ("Element count: ", len(contacts) ) 

contactsAsString = str(contacts)  
print ("str(contacts): ", contactsAsString )

# Một đối tượng đại diện lớp 'dict'.
aType = type(contacts) 
print ("type(contacts): ", aType )

# Hàm dir(dict) trả về các thành viên của lớp 'dict'. 
print ("dir(dict): ", dir(dict) )

# ------------------------------------------------------------------------------------
# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', 
#  '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', 
#  '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', 
#  '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
#  '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 
#  'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 
#  'setdefault', 'update', 'values']
# -------------------------------------------------------------------------------------

5- Các phương thức

  • TODO

Có thể bạn quan tâm

Đây là các khóa học trực tuyến bên ngoài website o7planning mà chúng tôi giới thiệu, nó có thể bao gồm các khóa học miễn phí hoặc giảm giá.