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 Python
  • Phương pháp 1: Sử dụng danh sách
  • Phương pháp 2: Sử dụng cho vòng lặp
  • Phương pháp 3: Sử dụng các mục ()
  • Phương pháp 4: Sử dụng Pandas DataFrame
  • Tài nguyên
  • Bàn luận
  • 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?
  • Làm thế nào để bạn truy cập dữ liệu từ một từ điển trong Python?
  • Làm thế nào để tôi giải nén một từ điển?
  • Làm cách nào để trích xuất các khóa và giá trị từ một từ điển?

Bốn phương pháp để trích xuất các khóa từ từ điển Python

Nó 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 is the dictionary with currency abbreviations as keys and currency names as value.

currency_dict={'USD':'Dollar',
'EUR':'Euro',
'GBP':'Pound',
'INR':'Rupee'}

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’.
For example, currency_dict[‘GBP’] will return ‘Pound’.

Phương pháp 1: Sử dụng danh sách

Phương pháp 2: Sử dụng cho vòng lặp
Step 2: Find the matching index from value list.
Step 3: Use the index to find the appropriate key from key list.

key_list=list(currency_dict.keys())
val_list=list(currency_dict.values())
ind=val_list.index(val)
key_list[ind]
Output: 'GBP'

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ặp

Phương pháp 3: Sử dụng các mục ()
Step 1: Convert dictionary keys and values into lists.
Step 2: Iterate through all values in value list to find the required value
Step 3: Return the corresponding key from the key list.

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'

Phương pháp 3: Sử dụng các mục ()

Phương pháp 4: Sử dụng Pandas DataFrame
Step 1: Iterate through all key-value pairs in item().
Step 2: Find the value which match the required value
Step 3: Return the key from the key-value pair.

def return_key(val):
for key, value in currency_dict.items():
if value==val:
return key
return('Key Not Found')
return_key('Dollar')Output: 'USD'

Phương pháp 4: Sử dụng Pandas DataFrame

Tài nguyên
However it is not the most efficient one, which in my opinion would be the one-liner in Method 1.
A dictionary can be converted into a pandas DataFrame as below:

df=pd.DataFrame({'abbr':list(currency_dict.keys()),
'curr':list(currency_dict.values())})

Bàn luận
Now finding the value is very easy, just return the value from ‘abbr’ column from the row where value of ‘curr’ column is the required value.

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 
Note that the output contains index as well. The output is not in string format but it is a pandas Series object type.

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]
df.abbr[df.curr==val].mode()[0]
df.abbr[df.curr==val].sum()
Output : 'GBP'

Tài nguyên

Mã 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 ..

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 

Một ví dụ:

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]

Tái bút: Vâng, tôi yêu

key_list=list(currency_dict.keys())
val_list=list(currency_dict.values())
ind=val_list.index(val)
key_list[ind]
Output: 'GBP'
2. ;-)

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc

    Bàn luận

    Chú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;

    Python3

    Phươ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())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    3
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    4
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    5
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    6
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    7
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    8__19
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    5
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    6
    list(currency_dict.keys())[list(currency_dict.values()).index(val)]
    4
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    9
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    6
    df=pd.DataFrame({'abbr':list(currency_dict.keys()),
    'curr':list(currency_dict.values())})
    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'
    2
    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'
    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'
    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'
    6
    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'
    7

    list(currency_dict.keys())[list(currency_dict.values()).index(val)]
    98
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    4
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    0
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    1
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    2
    def 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
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    48
    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    4
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    0
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    1
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    2
    def 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
    def return_key(val):
    for key, value in currency_dict.items():
    if value==val:
    return key
    return('Key Not Found')
    return_key('Dollar')Output: 'USD'
    4

    key_list=list(currency_dict.keys())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    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;

    Python3

    Phươ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())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    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())})6

    Là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())
    val_list=list(currency_dict.values())
    ind=val_list.index(val)
    key_list[ind]
    Output: 'GBP'
    2. ;-)

    Xem thảo luận

    Cả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.