On 30/07/18 19:11, Zachary Ware wrote:
> On Mon, Jul 30, 2018 at 1:08 PM Alan Gauld via Tutor <tutor@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,[])
             data.append(k)
             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
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to