Hướng dẫn check element exists in dictionary python - kiểm tra phần tử tồn tại trong từ điển python

Kiểm tra xem một khóa nhất định đã tồn tại trong từ điển

Để có ý tưởng làm thế nào để làm điều đó trước tiên chúng tôi kiểm tra những phương pháp nào chúng tôi có thể gọi trên từ điển.

Đây là các phương pháp:

d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary

Phương pháp tàn bạo để kiểm tra xem khóa đã tồn tại có thể là phương pháp ____1010 không:

d.get["key"]

Hai phương pháp thú vị khác

Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
1 và
Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
2 nghe có vẻ quá nhiều công việc. Vì vậy, hãy kiểm tra xem
Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
0 có phải là phương pháp phù hợp với chúng tôi không. Chúng tôi có Dict
Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
4 của chúng tôi:

d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

In hiển thị khóa mà chúng tôi không có sẽ trả về

Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
5:

print[d.get['key']] #None
print[d.get['clear']] #0
print[d.get['copy']] #1

Chúng tôi sử dụng điều đó để có được thông tin nếu khóa có mặt hoặc không. Nhưng hãy xem xét điều này nếu chúng ta tạo ra một dict với một

Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
6:

d= {'key':None}
print[d.get['key']] #None
print[d.get['key2']] #None

Dẫn đầu phương thức

Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
0 không đáng tin cậy trong trường hợp một số giá trị có thể là
Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
5.

Câu chuyện này nên có một kết thúc hạnh phúc hơn. Nếu chúng ta sử dụng bộ so sánh

Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
9:

print['key' in d] #True
print['key2' in d] #False

Chúng tôi nhận được kết quả chính xác.

Chúng tôi có thể kiểm tra mã Byte Python:

import dis
dis.dis["'key' in d"]
#   1           0 LOAD_CONST               0 ['key']
#               2 LOAD_NAME                0 [d]
#               4 COMPARE_OP               6 [in]
#               6 RETURN_VALUE

dis.dis["d.get['key2']"]
#   1           0 LOAD_NAME                0 [d]
#               2 LOAD_METHOD              1 [get]
#               4 LOAD_CONST               0 ['key2']
#               6 CALL_METHOD              1
#               8 RETURN_VALUE

Điều này cho thấy

Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
9 so sánh toán tử không chỉ đáng tin cậy hơn mà còn nhanh hơn
Python Dictionary clear[]        Removes all Items
Python Dictionary copy[]         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys[]     Creates dictionary from given sequence
Python Dictionary get[]          Returns Value of The Key
Python Dictionary items[]        Returns view of dictionary [key, value] pair
Python Dictionary keys[]         Returns View Object of All Keys
Python Dictionary pop[]          Removes and returns element having given key
Python Dictionary popitem[]      Returns & Removes Element From Dictionary
Python Dictionary setdefault[]   Inserts Key With a Value if Key is not Present
Python Dictionary update[]       Updates the Dictionary
Python Dictionary values[]       Returns view of all values in dictionary
0.

Đội câu trả lời giáo dục

LƯU Ý: Phương pháp được đề cập trong ảnh này, phương pháp Python

d.get["key"]
2, đã không còn phản đối và không có sẵn trong Python 3.

Một từ điển là một cấu trúc dữ liệu có giá trị trong Python; Nó giữ các cặp giá trị khóa. Trong quá trình lập trình, thường cần phải trích xuất giá trị của một khóa đã cho từ từ điển; Tuy nhiên, không phải lúc nào cũng đảm bảo rằng một khóa cụ thể tồn tại trong từ điển.

Khi bạn lập chỉ mục từ điển với một khóa không tồn tại, nó sẽ gây ra lỗi.

Do đó, đó là một thực tế an toàn để kiểm tra xem chìa khóa có tồn tại trong từ điển trước khi trích xuất giá trị của khóa đó hay không. Với mục đích đó, Python cung cấp hai chức năng tích hợp:

  • d.get["key"]
    
    3

  • ________ 24 -________ 19 Tuyên bố

1.
d.get["key"]
2

Phương thức

d.get["key"]
2 trả về true nếu một khóa nhất định có sẵn trong từ điển; Nếu không, nó trả về sai.

Cú pháp

Xem cú pháp của phương thức

d.get["key"]
2 bên dưới:

Mã số

Đoạn mã bên dưới minh họa việc sử dụng phương pháp

d.get["key"]
2:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}

key_to_lookup = 'a'

if Fruits.has_key[key_to_lookup]:

print "Key exists"

else:

print "Key does not exist"

Phương pháp

d.get["key"]
2 đã được loại bỏ khỏi Python3.

2. ________ 24 -________ 19 Tuyên bố

Cách tiếp cận này sử dụng câu lệnh ____ 24 -________ 19 để kiểm tra xem có phải một khóa nhất định có tồn tại trong từ điển hay không.

Cú pháp

Xem cú pháp của phương thức

d.get["key"]
2 bên dưới:

Mã số

Đoạn mã bên dưới minh họa việc sử dụng phương pháp

d.get["key"]
2:

Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}

key_to_lookup = 'a'

if key_to_lookup in Fruits:

print "Key exists"

else:

print "Key does not exist"

Làm thế nào để bạn kiểm tra xem một yếu tố tồn tại trong một từ điển?

Bạn có thể kiểm tra xem một khóa có tồn tại hay không trong từ điển bằng cách sử dụng câu lệnh IF-IN/trong toán tử, get [], khóa [], xử lý ngoại lệ 'keyerror' và trong các phiên bản cũ hơn python 3, sử dụng has_key []. 2.using if-in statement/in operator, get[], keys[], handling 'KeyError' exception, and in versions older than Python 3, using has_key[]. 2.

Làm thế nào để bạn kiểm tra xem khóa không tồn tại trong python từ điển?

Kiểm tra xem khóa có tồn tại bằng phương thức get [] Phương thức get [] là phương thức từ điển trả về giá trị của khóa liên quan. Nếu khóa không có mặt, nó sẽ trả về giá trị mặc định [nếu được thông qua] hoặc nó không trả về không. Sử dụng phương pháp này, chúng tôi có thể chuyển một khóa và kiểm tra xem một khóa có tồn tại trong từ điển Python không.using the get[] method The get[] method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value [if passed] or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.

Làm thế nào để bạn kiểm tra xem một từ nằm trong một python từ điển?

Để kiểm tra xem một chìa khóa có tồn tại trong từ điển Python, bạn có thể sử dụng toán tử trong để tìm kiếm thông qua các khóa từ điển như thế này: Thú cưng = {'Mèo': 1, 'Chó': 2, 'Cá': 3} nếu 'chó 'Trong thú cưng: In [' Chó tìm thấy! '] # Dogs tìm thấy! Một từ điển có thể là một cấu trúc dữ liệu thuận tiện để đếm sự xuất hiện của các mục.use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print['Dogs found!'] # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.

Làm thế nào để bạn kiểm tra xem một khóa có mặt trong một từ điển lồng nhau trong Python không?

Truy cập các mục từ điển lồng nhau này có thể được thực hiện bằng phương thức Get [] từ điển đặc biệt.Phương thức get [] trả về giá trị cho khóa nếu khóa nằm trong từ điển, nếu không, nó không trả về không.Do đó, chúng tôi không bao giờ nhận được KeyError nếu chúng tôi sử dụng phương pháp này.using the special dictionary get[] method. The get[] method returns the value for the key if the key is in the dictionary, otherwise, it returns None. Hence, we never get the keyError if we use this method.

Bài Viết Liên Quan

Chủ Đề