简体   繁体   中英

Find the dictionary keys that are present in the list

I am new to python object oriented programming. I am trying to solve a problem where I have to define a class, create a method, write the code inside it and then create a object and call that method. I am a little confused on how to go forward with it.

Example: {1:'A',2:'B} L: [1,2,3,4]

Find the dictionary keys that are present in the list (without using for loop)

Try this:

def match_keys(dct, lst):
    matches = list()
    
    for key in dct.keys():
        if key in lst:
            matches.append(key)
    
    return matches

Without for loop, you can use filter :

output = list(filter(lambda elem: elem in list(dct.keys()), lst))

Another simple approach can be to use intersection() :

my_dict = {1: 'A', 2: 'B'}
my_list = [1, 2, 3, 4]

output = set(my_dict).intersection(my_list)
print(output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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