Tricky Dictionary Question from newbie

Cyril Bazin cyril.bazin at gmail.com
Mon Jul 11 14:18:55 EDT 2005


Hello, 

Try that, it may not be the better solution, but it seems to work:

#def invertDict(d):
# d2 = {}
# for k, v in d.iteritems():
# d2.setdefault(v, []).append(k)
# return d2

Cyril

On 7/11/05, Ric Da Force <ric at next-level.com.au> wrote:
> 
> Hi all,
> 
> I have a dictionary containing about 300 items, some of the values being
> repeated. Both keys and values are strings. How can I turn this thing on
> its head so that we create a key based on each unique value and build the
> values based on the keys corresponding to the repeated values?
> 
> It is hard to explain but this is what I mean:
> 
> Dict = {'rt': 'This is repeated', 'sr': 'This is repeated', 'gf': 'This is
> not'}
> 
> I want this to return a new dict with string keys and lists containing the
> previous keys for repeated values.
> 
> NewDict = {'This is repeated':['rt','sr'],'This is not':['gf']}
> 
> I am still learning Python and have struggled with this for hours before
> deciding to go for help. Unfortunately, I didn't really know how to search
> for this in google and decided to post it here. I apologise if this is too
> basic for this newsgroup...
> 
> Ric
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20050711/6a5e2920/attachment.html>


More information about the Python-list mailing list