Since your keys are not unique, I would think that you would want a list of values for the object corresponding to each key. Something like
Mydict = {} Mydict.setdefault(mykey, []).append(avalue) -----Original Message----- From: python-list-bounces+frsells=adventistcare....@python.org [mailto:python-list-bounces+frsells=adventistcare....@python.org] On Behalf Of Peter Otten Sent: Sunday, November 07, 2010 4:01 PM To: python-list@python.org Subject: Re: { '0':'c->c->a' ,'1':'a->b->a' .........} 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 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list