How to remove duplicate values from defaultdict(int) in python? -


i have dictionary consists of unique key value pairs follows:

    edu_bg={1: 1, 2: 2, 3: 1, 4: 1, 5: 2, 6: 2} 

i want create dictionary above data similar records (which has similar values) grouped follows:

   {(1, 3): 1, (5, 6): 1, (1, 4): 1, (2, 6): 1,(2, 5): 1, (3, 4): 1}) 

i tried achieve above output using following code:

    myedu = defaultdict(int)     k,v in edu_bg.iteritems():         k,v in edu_bg.iteritems():           if k == k , v == v:               pass           if k != k , v == v:               myedu[(k,k)] += 1           else:               pass 

however has resulted in duplicate records follows:

         defaultdict(<type 'int'>, {(1, 3): 1, (5, 6): 1, (4, 1): 1, (3, 1): 1, (5, 2): 1, (1, 4): 1, (2, 6): 1, (4, 3): 1, (6, 2): 1, (2, 5): 1, (3, 4): 1, (6, 5): 1}) 

i want remove these duplicate values. advice on problem appreciated.

instead of iterating on cartesian product of every pair, iterated on n^2 elements, iterate on every possible combination, iterate on n(n-1)/2 elements. while big oh complexity same, constant factors reduced significantly:

>>> collections import defaultdict >>> itertools import combinations >>> myedu = defaultdict(int) >>> edu_bg={1: 1, 2: 2, 3: 1, 4: 1, 5: 2, 6: 2} >>> k1,k2 in combinations(edu_bg,2): ...   if edu_bg[k1] == edu_bg[k2]: ...     myedu[(k1,k2)] += 1 ...  >>> myedu defaultdict(<class 'int'>, {(2, 6): 1, (1, 3): 1, (5, 6): 1, (2, 5): 1, (3, 4): 1, (1, 4): 1}) >>>  

i should reiterate, though, sounds xy problem...


Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

laravel - Undefined property: Illuminate\Pagination\LengthAwarePaginator::$id (View: F:\project\resources\views\admin\carousels\index.blade.php) -