soo this is the parameter type "symmetric_difference: (dict, dict) -> dict" and the description is "Return a new dict that contains all of the {key:value} pairs whose key is a key in one of the input dictionaries, but not in both."
my code that i made and it works is def symmetric_difference(dict1,dict2): """(dict, dict) -> dict""" newD = {} for x in dict1.keys(): if x in dict2: pass else: newD[x] = dict1.get(x) for x in dict2.keys(): if x in dict1: pass else: newD[x] = dict2.get(x) return newD but wondering is there a easier way? like you showed before
@shandelman
The answer is "Yes, but you probably did it the easiest way there is knowing what you know now." Let me see if I can whip up a shorter way...it will probably have to do with sets.
Here's my short answer. I have a feeling we can get even shorter...I'll have to think about it. def symmetric_difference(d1,d2): xor_set = set(d1)^set(d2) d1.update(d2) return {key:value for key,value in d1.items() if key in xor_set} 1. I turned each of the dictionaries into sets so that I could use the "^" operator, which returns a set containing the values that are in one or the other but not both. 2. I put all of the elements of d2 into d1 to get one long dictionary with all of the elements. Note that this actually gets rid of duplicates since you can't have a key twice, but we still need to get rid of those duplicates. 3. I return a new dictionary that has all the elements of d1, AS LONG AS they are also in that set I created earlier. I had to learn some new stuff to do this...for example, I didn't even know there was such a thing as dictionary comprehension as I used in the last line. Your professor would not expect an answer like this, and would actually probably get kinda suspicious if you used it, so I'd go with your solution. I'm only showing you this to show you that there's always a quicker, easier way to do something, AND that if you don't know how to do something, a little research goes a long way. I actually had to look a bunch up to manage my version of the function! :)
(I realize I said "get rid of duplicates" twice...I meant the update makes it so there are only one of each duplicate, but we actually want 0 of each duplicate).
If we wanted to get really silly, here's a one-liner that does pretty much the same thing: def symmetric_difference(d1,d2): return {key:value for key,value in d1.items()+d2.items() if (key in d1 and key not in d2) or (key in d2 and key not in d1)} (That's not two lines, that's just one really long line)
awesome thanks a lott :)
No prob.
Join our real-time social learning platform and learn together with your friends!