[Tutor] Dictionary viceversa

Valerio Pachera valerio at pbds.eu
Mon Jul 30 08:40:45 EDT 2018


Hi all, consider this dictionary

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.

Generalizing, a dictionary with a list for each element.

d = {k:list}

I wish to get the same info but "sorted" by room.
In other words, a dictionary that has rooms as keys.
For each room there's a list of users that can access the room.

I've been able to achieve that by

for user in users:
    for room in users[user]:
        if room in users_by_room:
            users_by_room[room].append(user)
        else:
            users_by_room[room] = []
            users_by_room[room].append(user)

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?
Maybe by list comprehension?

I was looking to substiture the cicle for e in new_d like this:
  [ new_d[e].append(k) if e in new_d else new_d[e].append(k) for e in d[k] ]
but it can't work because 'new_d[e] = []' is missing.



More information about the Tutor mailing list