+ 1

Filter and lambda expressions with dictionaries. Update: Answered

Hi You all, I have the following questions. I have a dictionary with disney figures and I would like to filter out all the names that are not 'Klaartje' # declaring dictionary 1 figures = {'chicken':'Klaartje', 'horse': 'Karel', 'duck' : 'Donald'} # def function that filters all options from which the value of the item is equal to 'Klaartje' by using # item[1] and figures.items() 2 k_names = dict(filter(lambda item:item[1] == 'Klaartje', figures.items())) 3 print(k_names) Output {'chicken': 'Klaartje'} Now I try to generate the same output but in a different way # def function that filters all options from which the value of the item is equal to 'Klaartje' by using # value and figures.values() 2 k_names = dict(filter(lambda value : value == 'Klaartje', figures.values())) 3 print(k_names) This time, I get an error. Same happens when I try to filter out by keys. # def function that filters all options from which the key of the item is equal to 'horse' by using # key and figures.keys() 2 k_names = dict(filter(lambda key : key == 'horse', figures.keys())) 3 print(k_names) Does anyone know if this is even possible, and if so, how? The reason I want to know, is because I would like to filter out not just the names that are not 'Klaartje', but al the names that do not start with a 'K'. Normally you would use name[0} != 'K', but now I use the [] for to determine the key/value of the item I am iterating over, so this does not work. I hope one of you can help me. Thankyou in advance!

9th Jul 2024, 9:19 AM
Keetie
11 Réponses
+ 8
Keetie , to get all items from the dict where values start with a `K`, we can just replace a part of the current filter expression: ... item: item[1] == 'Klaartje' ...=> ... item: item[1].startswith('K') ... k_names = dict(filter(lambda item: item[1] == 'Klaartje', figures.items())) > result will be: {'chicken': 'Klaartje'} k_names = dict(filter(lambda item: item[1].startswith('K'), figures.items())) > result will be: {'chicken': 'Klaartje', 'horse': 'Karel'}
9th Jul 2024, 10:46 AM
Lothar
Lothar - avatar
+ 5
Keetie , no, there is no special function for searching for a substring in the dictionary values. but we can use the membership operator `in`. to get it done we can filter for the letter `a` like: ... k_names = dict(filter(lambda item: 'a' in item[1], figures.items())) > result will be: {'chicken': 'Klaartje', 'horse': 'Karel', 'duck': 'Donald'} >> to make the filtering with the dicts a bit more general, we can use input values, store them in a variable,and use this variable instead of the *hardcoded* samples we have been talking so far.
9th Jul 2024, 2:32 PM
Lothar
Lothar - avatar
+ 4
if you are looking for more complex patterns than startswith(), endswith(), and "in", consider "regular expressions" (not sure if it is covered in the current courses?).
9th Jul 2024, 1:29 PM
Lisa
Lisa - avatar
+ 4
Lisa , regex is *not* explained in the current available python tutorials. maybe in an upcoming new / advanced tutorial ...
9th Jul 2024, 2:52 PM
Lothar
Lothar - avatar
+ 3
Here is the SoloLearn lesson about list comprehension which is very similar to dict comprehension. https://www.sololearn.com/learn/o-JUMP_LINK__&&__Python__&&__JUMP_LINK/2454/?ref=app For example: k_names = {k: v for k, v in figures.items() if v == 'Klaartje'}
9th Jul 2024, 10:29 AM
Stefanoo
Stefanoo - avatar
+ 3
Lisa, Stefanoo, Thnx for the help! No it's not necessary to use filter, but I was doing the SoloLearn lesson on map and filter and when they came up with the example of filtering from a dictionary, I was just curious to find out how I could use these functions in this new filter situation. I know I probably could have tried the list comprehension, but then I still wouldn't have known how it works with filtering a dictionary :)
9th Jul 2024, 12:47 PM
Keetie
+ 2
is it crucial to use filter()? a dictionary entry needs always key and values, so we need to make sure that something is returned for the filtered part... i think I would attempt a loop or a dict comprehension first, just to get a better idea of what happens.
9th Jul 2024, 9:59 AM
Lisa
Lisa - avatar
+ 2
Hi Lothar, Thankyou very much! I didn't know this function yet, so I've learned something new. I also tried item[1].endswith('d') and that also worked. Is there also a function for anything in between? I guessed item[1].with and item[1].within('al') tot get 'Donald', but these did not work and I can't find it anywhere else. Thank you for your help so far, really appreciate it!
9th Jul 2024, 12:43 PM
Keetie
+ 1
It's very good to have detailed context in the description and I'm sure you get your answer right. Just as Lisa pointed out, filter isn't the best method especially when working with large dictionary, but since it's just to practice, so it's fine. In an actual real setup, you will need to use the C datatype of python to achieve a more efficient result Import ctype # use structures and C datatype with dict comprehension and array indexing
9th Jul 2024, 10:17 PM
Mel
+ 1
Hii Melle, Thnx, you're probably right, but I really don't understand any of the things (datatype C, importing data types, array indexing) you say haha. I'm having a really hard time trying to figure out when to use what, especially since I have no computer/programming experience at all. I'll just try to finish the course and see what I can understand :)
12th Jul 2024, 2:02 PM
Keetie