Hướng dẫn extract from dictionary python - trích xuất từ python từ điển
Nội dung chính Show
Bốn phương pháp để trích xuất các khóa từ từ điển PythonNó là thẳng để trích xuất giá trị nếu chúng ta có khóa, như mở khóa khóa bằng một khóa. Tuy nhiên, ngược lại, ngược lại, không đơn giản, giống như không biết gì về khóa với khóa, có lẽ! Đôi khi việc trích xuất các khóa trở nên quan trọng, đặc biệt là khi khóa và giá trị có mối quan hệ một-một. Đó là, khi một trong hai người là duy nhất và do đó có thể đóng vai trò là chìa khóa. Trước khi đi vào các phương pháp khác nhau, trước tiên chúng tôi sẽ tạo ra một từ điển cho mục đích minh họa. Tiền tệ_DICT là từ điển có chữ viết tắt tiền tệ làm khóa và tên tiền tệ là giá trị.currency_dict is the dictionary with currency abbreviations as keys and currency names as value. currency_dict={'USD':'Dollar', Nếu bạn có chìa khóa, nhận được giá trị bằng cách thêm khóa trong khung vuông. Ví dụ, CRINCENTY_DICT [‘GBP,] sẽ trả về‘ pound.For example, currency_dict[‘GBP’] will return ‘Pound’. Phương pháp 1: Sử dụng danh sáchPhương pháp 2: Sử dụng cho vòng lặp key_list=list(currency_dict.keys()) Phương pháp 3: Sử dụng các mục () list(currency_dict.keys())[list(currency_dict.values()).index(val)] Phương pháp 2: Sử dụng cho vòng lặpPhương pháp 3: Sử dụng các mục () def return_key(val): Phương pháp 3: Sử dụng các mục ()Phương pháp 4: Sử dụng Pandas DataFrame def return_key(val): Phương pháp 4: Sử dụng Pandas DataFrameTài nguyên df=pd.DataFrame({'abbr':list(currency_dict.keys()), Bàn luận df.abbr[df.curr==val]Output: 2 GBP def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'2def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'3df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})3 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'5 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'6df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})6 Làm cách nào để trích xuất một khóa từ điển trong Python? df.abbr[df.curr==val].unique()[0] Tài nguyênMã cho bài viết này có sẵn trong repo GitHub của tôi. Bạn có thể xem video YouTube của tôi nếu bạn quan tâm hơn đến định dạng trực quan Hướng dẫn YouTube của tác giảSử dụng toán tử giải nén (**) để giải nén từ điển trong Python ..
Một ví dụ:
Tái bút: Vâng, tôi yêu key_list=list(currency_dict.keys())2. ;-) Xem thảo luận Cải thiện bài viết Lưu bài viết Xem thảo luận Cải thiện bài viết Lưu bài viết Đọc Bàn luậnChúng tôi có rất nhiều biến thể và ứng dụng của các thùng chứa từ điển trong Python và đôi khi, chúng tôi muốn thực hiện một bộ lọc các phím trong từ điển, i.e chỉ trích xuất các khóa có trong thùng chứa cụ thể. Hãy để thảo luận về những cách nhất định trong đó điều này có thể được thực hiện. & NBSP; Python3Phương pháp 1: Trích xuất các khóa cụ thể từ từ điển bằng cách hiểu từ điển + các mục () Vấn đề này có thể được thực hiện bằng cách tái tạo bằng cách sử dụng các khóa được trích xuất thông qua hàm các mục muốn được lọc và hàm từ điển làm cho từ điển mong muốn. key_list=list(currency_dict.keys())3 key_list=list(currency_dict.keys())4 key_list=list(currency_dict.keys())5 key_list=list(currency_dict.keys())6 key_list=list(currency_dict.keys())7 key_list=list(currency_dict.keys())8__19 def return_key(val):5 def return_key(val):6 list(currency_dict.keys())[list(currency_dict.values()).index(val)] 4key_list=list(currency_dict.keys())9 key_list=list(currency_dict.keys())6 df=pd.DataFrame({'abbr':list(currency_dict.keys()), 0def return_key(val):2 def return_key(val):3 def return_key(val):4 def return_key(val):5 def return_key(val):6 def return_key(val):7 list(currency_dict.keys())[list(currency_dict.values()).index(val)] 98key_list=list(currency_dict.keys())4 def return_key(val):0 def return_key(val):1 def return_key(val):2 def return_key(val):3 def return_key(val):48 key_list=list(currency_dict.keys())4 def return_key(val):0 def return_key(val):1 def return_key(val):2 def return_key(val):3 def return_key(val):4 key_list=list(currency_dict.keys())0 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'2def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'3df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})3 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'5 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'6df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})6Đầu ra: & nbsp; Python3Phương pháp 1: Trích xuất các khóa cụ thể từ từ điển bằng cách hiểu từ điển + các mục () Vấn đề này có thể được thực hiện bằng cách tái tạo bằng cách sử dụng các khóa được trích xuất thông qua hàm các mục muốn được lọc và hàm từ điển làm cho từ điển mong muốn.Đầu ra: & nbsp; key_list=list(currency_dict.keys())0 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'2def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'3def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'4 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'5 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'6def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'7def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR' 8key_list=list(currency_dict.keys())val_list=list(currency_dict.values())ind=val_list.index(val)key_list[ind]Output: 'GBP'4 from typing import Iterable def get_all_values(d): if isinstance(d, dict): for v in d.values(): yield from get_all_values(v) elif isinstance(d, Iterable): # or list, set, ... only for v in d: yield from get_all_values(v) else: yield d 4from typing import Iterable def get_all_values(d): if isinstance(d, dict): for v in d.values(): yield from get_all_values(v) elif isinstance(d, Iterable): # or list, set, ... only for v in d: yield from get_all_values(v) else: yield d 5def return_key(val): for key, value in currency_dict.items(): if value==val: return key return('Key Not Found')return_key('Dollar')Output: 'USD'1d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': set([6, 7])}]} list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6, 7] 4d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': set([6, 7])}]} list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6, 7] 5 from typing import Iterable def get_all_values(d): if isinstance(d, dict): for v in d.values(): yield from get_all_values(v) elif isinstance(d, Iterable): # or list, set, ... only for v in d: yield from get_all_values(v) else: yield d 7def return_key(val): for key, value in currency_dict.items(): if value==val: return key return('Key Not Found')return_key('Dollar')Output: 'USD'3 d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': set([6, 7])}]} list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6, 7] 8def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'2def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'3df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})3 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'5 def return_key(val): for i in range(len(currency_dict)): if val_list[i]==val: return key_list[i] return("Key Not Found")return_key("Rupee")Output: 'INR'6df=pd.DataFrame({'abbr':list(currency_dict.keys()), 'curr':list(currency_dict.values())})6Làm cách nào để trích xuất một khóa từ điển trong Python?Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list. Phương pháp 1: Sử dụng danh sách. Bước 1: Chuyển đổi các khóa và giá trị từ điển thành danh sách. Bước 2: Tìm chỉ mục phù hợp từ danh sách giá trị. Bước 3: Sử dụng chỉ mục để tìm khóa thích hợp từ danh sách khóa.Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.Làm thế nào để bạn truy cập dữ liệu từ một từ điển trong Python?. Để truy cập giá trị từ điển trong Python, bạn có ba tùy chọn:.. Sử dụng từ điển.Giá trị () phương thức để có được tất cả các giá trị .. Sử dụng dấu ngoặc vuông [] để nhận một giá trị duy nhất (không hoàn toàn) .. Sử dụng từ điển.nhận () phương thức để nhận một giá trị một cách an toàn từ một từ điển ..Làm thế nào để tôi giải nén một từ điển?. Sử dụng toán tử giải nén (**) để giải nén từ điển trong Python .. Một ví dụ: Tái bút: Vâng, tôi yêu key_list=list(currency_dict.keys())2. ;-) Xem thảo luậnCải thiện bài viếtusing the items function which does the task of extracting a key-value pair and using the 0th index gives us the first key-value pair. Works only in Python2. The combination of above functions can be used to perform this particular task. It uses iterators to perform this task. |