{ '0':'c->c->a' ,'1':'a->b->a' .........}

Peter Otten __peter__ at web.de
Sun Nov 7 22:00:38 CET 2010


chris wrote:
> have anybody a hint , how i get a dict from non unique id's and their
> different related values.
> 
> Thanks for advance
> Chris
> 
> ###random data #
> a=range(10)*3
> def seqelem():
>     i=random.randint(0,2)
>     elem=['a','b','c'][i]
>     return elem
> 
> s=[seqelem() for t in  range(30)]
> print zip(a,s)
> 
> ## favored result:
> { '0':'c->c->a' ,'1':'a->b->a' .........}

>>> import random
>>> from collections import defaultdict
>>> a = range(10)*3
>>> s = [random.choice("abc") for _ in a]
>>> d = defaultdict(list)
>>> for k, v in zip(a, s):
...     d[k].append(v)
...
>>> d
defaultdict(<type 'list'>, {0: ['b', 'a', 'a'], 1: ['c', 'a', 'c'], 2: ['c', 
'c', 'c'], 3: ['c', 'a', 'a'], 4: ['b', 'c', 'a'], 5: ['b', 'c', 'c'], 6: 
['c', 'a', 'b'], 7: ['b', 'b', 'a'], 8: ['a', 'c', 'c'], 9: ['b', 'a', 
'b']})
>>> dict((k, "->".join(v)) for k, v in d.iteritems())
{0: 'b->a->a', 1: 'c->a->c', 2: 'c->c->c', 3: 'c->a->a', 4: 'b->c->a', 5: 
'b->c->c', 6: 'c->a->b', 7: 'b->b->a', 8: 'a->c->c', 9: 'b->a->b'}

Peter



More information about the Python-list mailing list