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

Peter Otten __peter__ at web.de
Tue Nov 9 19:14:15 CET 2010

```macm wrote:

> Hi Folks,
>
> dict1 = {'ab':[[1,2,3,'d3','d4',5],12],'ac':[[1,3,'78a','79b'],
> 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]}
> dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
> [[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}
> intersect = filter(dict1.has_key, dict2.keys())
> intersect
> result:
> ['ax', 'ac', 'ab']
>
> expect result dict1 intersection with dict2
> {'ac':[1,3,'79b'], 'ab':[2,'d3']} # look last key/value 'ax' (dict1,
> dict2) even intersec a key but not values from list so not valid
>
> and difference from dict3
> dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
> [[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}
>
> result from (intersect - dict3)
> {'ac':['79b'], 'ab':[2,'d3']}
>
>
> Before someone blame me.
>
> Yes I am trying learn python Functional Programming! ; )

>>> dict((k, v) for k, v in ((k, [a for a in v if a in w]) for k, v, w in
((k, v[0], set(dict2[k][0])) for k, v in dict1.iteritems() if k in dict2))
if v)
{'ac': [1, 3, '79b'], 'ab': [2]}

Replacing the genexps with map/filter/lambda is left as an exercise.

> Before someone blame me.

I'm trying to set new standards in readability ;)

```