[Tutor] Dictionary viceversa

Peter Otten __peter__ at web.de
Mon Jul 30 13:45:36 EDT 2018


Zachary Ware wrote:

> On Mon, Jul 30, 2018 at 12:20 PM Valerio Pachera <valerio at pbds.eu> wrote:
>> 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.
> 
> Have a look at `dict.setdefault` and play around with it; I think it
> will help you do what you want.

Either that, or use a defaultdict:
 
>>> import collections
>>> room_access = collections.defaultdict(list)
>>> for user, rooms in users.items():
...     for room in rooms:
...         room_access[room].append(user)
... 
>>> room_access
defaultdict(<class 'list'>, {'office-c': ['user3'], 'office-b': ['user2', 
'user1'], 'office-a': ['user3', 'user1']})




More information about the Tutor mailing list