Extract duplicate values ​​from a dictionary

I am trying to find a way to remove duplicate shaders in Maya using Python Dictionaries.

That's what I'm doing:

I want to put all Maya shaders in the dictionary as keys and put the corresponding texture file as a value. Then I want the script to work through a dictionary and find any keys that have the same value and put them in an array or another dictionary.

Basically this is what I have now:

shaders_dict = {'a': somePath, 'b': somePath,
                'c': differentPath, 'd': differentPath}

duplicate_shaders_dict = {}`

how can I now run this dictionary to compile another dictionary that looks something like this:

duplicate_shaders_dict = {'b':somePath, 'd':differentPath }

And this difficult part, since there are duplicates, I want the script up skip the original key, so it does not fill out to duplicate the shader dictionary either.

+5
source share
2

, , - . :

>>> from collections import defaultdict
>>> 
>>> shaders_dict = {'a':'somePath', 'b':'somePath', 'c':'differentPath', 'd':'differentPath'}
>>> 
>>> inverse_dict = defaultdict(list)
>>> for k,v in shaders_dict.iteritems():
...     inverse_dict[v].append(k)
... 
>>> inverse_dict
defaultdict(<type 'list'>, {'differentPath': ['c', 'd'], 'somePath': ['a', 'b']})

, , , .

:

>>> first_shaders_dict = {}
>>> duplicate_shaders_dict = {}
>>> for v, ks in inverse_dict.iteritems():
...     first, rest = ks[0], ks[1:]
...     first_shaders_dict[first] = v
...     for r in rest:
...         duplicate_shaders_dict[r] = v
... 
>>> first_shaders_dict
{'a': 'somePath', 'c': 'differentPath'}
>>> duplicate_shaders_dict
{'b': 'somePath', 'd': 'differentPath'}

. , . , . , @freespace , , , .

-

: . itertools:

>>> import itertools
>>> shaders_dict = {'a':'somePath', 'b':'somePath', 'c':'differentPath', 'd':'differentPath'}
>>> keys = sorted(sorted(shaders_dict),key=shaders_dict.get)
>>> by_val = [(v, list(ks)) for v, ks in itertools.groupby(keys, shaders_dict.get)]
>>> first_dict = dict((ks[0],v) for v,ks in by_val)
>>> duplicate_dict = dict((k,v) for v,ks in by_val for k in ks[1:])
>>> first_dict
{'a': 'somePath', 'c': 'differentPath'}
>>> duplicate_dict
{'b': 'somePath', 'd': 'differentPath'}
+4

. :

>>> d = {'a': 'somePath', 'b': 'somePath', 
... 'c': 'differentPath', 'd': 'differentPath'}

:

>>> r = dict((v,k) for k,v in d.iteritems())

:

>>> r
{'differentPath': 'd', 'somePath': 'b'}

And if you cancel this, you have the original dictionary with duplicates deleted:

>>> d = dict((v,k) for k,v in r.iteritems())
>>> d
{'b': 'somePath', 'd': 'differentPath'}
+3
source

All Articles