Hướng dẫn python dict without key

We can delete a key from a Python dictionary by the some of the following approaches.

Using the del keyword; it's almost the same approach like you did though -

 myDict = {'one': 100, 'two': 200, 'three': 300 }
 print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
 if myDict.get('one') : del myDict['one']
 print(myDict)  # {'two': 200, 'three': 300}

Or

We can do like the following:

But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making a specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.

myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}

If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

var = {key:value for key, value in myDict.items() if key != 'one'}

Now if we try to print it, then it'll follow the parent order:

print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

Or

Using the pop() method.

myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)

if myDict.get('one') : myDict.pop('one')
print(myDict)  # {'two': 200, 'three': 300}

The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100

Fork this gist for future reference, if you find this useful.

Mục lục

Hướng dẫn python dict without key
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ướng dẫn python dict without key
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.
Hướng dẫn python dict without key
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.

Hướng dẫn python dict without key

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

Hướng dẫn python dict without key

Để 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)

Hướng dẫn python dict without key

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']
# -------------------------------------------------------------------------------------

Hướng dẫn python dict without key

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