python - Group similar dict entries as a tuple of keys -


i group similar entries of dataset.

ds = {1: 'foo',       2: 'bar',       3: 'foo',       4: 'bar',       5: 'foo'}  >>>tupelize_dict(ds) {    (1,3,5): 'foo',    (2,4): 'bar' } 

i wrote function, sure there way simpler, isn't?

def tupelize_dict(data):     itertools import chain, combinations     while true:         rounds = []         x in combinations(data.keys(), 2):             rounds.append((x, data[x[0]], data[x[1]]))          end = true         k, a, b in rounds:             if == b:                 k_chain = [x if isinstance(x, (tuple, list)) else [x] x in k]                 data[tuple(sorted(chain.from_iterable(k_chain)))] =                 [data.pop(r) r in k]                 end = false                 break         if end:             break     return data   

edit

i interested in general case content of dataset can type of object allows ds[i] == ds[j]:

ds = {1: {'a': {'b':'c'}},       2: 'bar',       3: {'a': {'b':'c'}},       4: 'bar',       5: {'a': {'b':'c'}}} 

something should trick:

>>> collections import defaultdict >>> ds = {1: 'foo', ...       2: 'bar', ...       3: 'foo', ...       4: 'bar', ...       5: 'foo'} >>> >>> d = defaultdict(list) >>> k, v in ds.items(): ...     d[v].append(k) ... >>> res = {tuple(v): k k, v in d.items()} >>> res {(1, 3, 5): 'foo', (2, 4): 'bar'} 

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

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

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -