[Tutor] Dictionary viceversa
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Jul 30 14:06:10 EDT 2018
On 30/07/18 13:40, Valerio Pachera wrote:
> users = {'user1':['office-a', 'office-b'],
> 'user2':['office-b'],
> 'user3':['office-a','office-c']}
>
> It's a list of users.
> For each user there's a list of room it can access to.
>
> I wish to get the same info but "sorted" by room.
Remember that dicts are not sorted. You can create a dictionary
keyed by room but not sorted by room.
(You can however get a list of sorted keys but that's different,
and you can use a collections.OrderedDict)
> And i generalized it in a function like this:
>
> def viceversa(d):
> new_d = dict()
> for k in d:
> for e in d[k]:
> if e in new_d:
> new_d[e].append(k)
> else:
> new_d[e] = []
> new_d[e].append(k)
> return(new_d)
>
> My question is: is there a better way to that?
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)
return(new_d)
> Maybe by list comprehension?
I can't think of a reasonable way of doing that but a
generator may work.
Another option would be to build a set of the original
rooms then iterate over the data, collecting the keys
which have those rooms. But that would be pretty
inefficient...
--
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
More information about the Tutor
mailing list