简体   繁体   English

将列表项与字典键进行比较,如果该项存在于字典中,则打印出键的值

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

Example code:示例代码:

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

Expected result:预期结果:

['Mango', 'Pear']

You can retrieve multiple keys at once, by using operator.itemgetter :您可以使用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)

Outputs:输出:

>>> res

('Mango', 'Pear')

You can use a simple loop, ask if there is a key with the same value and print it, for example:你可以使用一个简单的循环,询问是否有一个具有相同值的键并打印它,例如:

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

One approach would be to use a list comprehension to construct the requested list.一种方法是使用list comprehension来构建请求的列表。
Essentially we iterate through the list in the outer loop, and through the dictionary in the inner loop and then we compare the list value with the key from the dictionary , and should we have a match, then we save the value of the associated key in the new output list.本质上,我们在外循环中遍历list ,在内循环中遍历dictionary ,然后将list值与dictionarykey进行比较,如果匹配,则将关联key的值保存在新的输出列表。

This code snippet below works as described above:下面的代码片段按上述方式工作:

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)

When run it prints:运行时打印:

['Mango', 'Pear']

I personally don't believe in giving outright answers so I will give you a hint:我个人不相信给出直接的答案,所以我会给你一个提示:

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

I believe that should be enough for you to figure out the rest.我相信这应该足以让你弄清楚其余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM