Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

Alexander Gattin xrgtn at yandex.ru
Thu Nov 11 04:51:33 EST 2010


Hello,

On Tue, Nov 09, 2010 at 09:32:17AM -0800, macm wrote:
> dict1 = {'ab':[[1,2,3,'d3','d4',5],12],'ac':[[1,3,'78a','79b'],
> 54],'ad': [[56,57,58,59],34], 'ax': [[56,57,58,59],34]}
> dict2 = {'ab':[[22,2,'a0','42s','c4','d3'],12],'ab':[[2,4,50,42,'c4'],
> 12],'ac':[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34],'ax':
> [[9],34]}

You have a problem here: key 'ab' is listed twice
in dict2 and only its second value is then
visible: [[2,4,50,42,'c4'], 12], so that I
couldn't get the desired {'ac':[1,3,'79b'],
'ab':[2,'d3']} intersection.

So, after I've found the problem, the desired
functional-style code emerges:

> >>> dict(filter(lambda t: t[1],
> ...     map(lambda k: (k, filter(lambda v: v in dict2[k][0], dict1[k][0])),
> ...        filter(dict2.has_key, dict1.iterkeys()))
> ...        )
> ...     )
> {'ac': [1, 3, '79b'], 'ab': [2, 'd3']}
> >>> 

-- 
With best regards,
xrgtn



More information about the Python-list mailing list