簡體   English   中英

將列表項與字典鍵進行比較,如果該項存在於字典中,則打印出鍵的值

[英]Compare list item with a dictionary key and print out the value of the key if the item exists in the dictionary

示例代碼:

my_dict = {'ABC':'Apple','DEF':'Mango','GHI':'Pear','JKL':'Orange','MNO':'Plum'}
lst_x =  ['DEF','GHI']

預期結果:

['Mango', 'Pear']

您可以使用operator.itemgetter一次檢索多個鍵:

from operator import itemgetter

my_dict = {'ABC':'Apple','DEF':'Mango','GHI':'Pear','JKL':'Orange','MNO':'Plum'}

lst_x = ['DEF','GHI']
# in case, if there's a chance, that lst_x would get some of the keys, that are not in my_dict - add the below line:
# lst_x=set(lst_x).intersection(set(my_dict.keys()))
res=itemgetter(*lst_x)(my_dict)

輸出:

>>> res

('Mango', 'Pear')

你可以使用一個簡單的循環,詢問是否有一個具有相同值的鍵並打印它,例如:

my_dict = {'ABC':'Apple','DEF':'Mango','GHI':'Pear','JKL':'Orange','MNO':'Plum'}
lst = ['ABC','DEF','GHI','JKL','MNO']

for key in lst:
    if key in my_dict.keys():
        print(key, '->' , my_dict[key])

>>> ABC -> Apple
>>> DEF -> Mango
>>> GHI -> Pear
>>> JKL -> Orange
>>> MNO -> Plum

一種方法是使用list comprehension來構建請求的列表。
本質上,我們在外循環中遍歷list ,在內循環中遍歷dictionary ,然后將list值與dictionarykey進行比較,如果匹配,則將關聯key的值保存在新的輸出列表。

下面的代碼片段按上述方式工作:

my_dict = {'ABC':'Apple','DEF':'Mango','GHI':'Pear','JKL':'Orange','MNO':'Plum'}
lst_x = ['DEF','GHI']

out = [value for element in lst_x for key, value in my_dict.items() if element == key]
print(out)

運行時打印:

['Mango', 'Pear']

我個人不相信給出直接的答案,所以我會給你一個提示:

// for x in lst: 
//   if x in dictionary then
//     lst_x.append(x)

我相信這應該足以讓你弄清楚其余的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM