The two dictionaries mydict1
and mydict2
are given. Key-value-pairs in mydict2
should be removed if the values are already contained in mydict1
, regardless of the key and regardless of the order of the values.
The code below delivers the correct output mydict2 = {'key6': [2,1,4], 'key4': [2]}
. However, it will be used as part of a larger code. Is there is a better, i.e. more phytonic, way to write it in order to make it more compact and effective without the need of functions?
mydict1 = {'key1':[1],'key2':[1,2],'key3':[1,2,3]}
mydict2 = {'key4':[2],'key5':[2,1],'key6':[2,1,4]}
mydict3 = {}
for md2 in mydict2:
isindict = False
for md1 in mydict1:
isindict = isindict|(sorted(mydict1[md1])==sorted(mydict2[md2]))
if not isindict:
mydict3[md2] = mydict2[md2]
mydict2 = mydict3
The solutions for removing items from a list, comparison of dictionaries and conditional filtering of a dictionary are not transferable in a straightforward way.