[Tutor] Dictionary viceversa

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jul 30 14:36:49 EDT 2018

On 30/07/18 19:11, Zachary Ware wrote:
> On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor <tutor at python.org> wrote:
>> There are lots of options including those suggested elsewhere.
>> Another involves using get() which makes your function
>> look like:
>> def viceversa(d):
>>     new_d = dict()
>>     for k in d:
>>         for e in d[k]:
>>             new_d[e] = new_d.get(e,[]).append(k)
> Note that this will set each entry to `None` as returned by `list.append`.

Oops, yes. You need an intermediate variable:

         for e in d[k]:
             data = new_d.get(e,[])
             new_d[e] = data

Or use addition:

         for e in d[k]:
             new_d[e] = new_d.get(e,[]) + [k]

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list