Reputation: 23
My original dictionary is dict1.
dict1={'Input.txt':'Randy','Code.py':'Stan','Output.txt':'Randy'}
I need the output as below
{'Randy':['Input.txt','Output.txt'],'Stan':['Code.py']}
Upvotes: 2
Views: 228
Reputation: 20424
Neat Python skills:
dict1 = {'Input.txt':'Randy','Code.py':'Stan','Output.txt':'Randy'}
out = {}
for k, v in dict1.items():
out.setdefault(v, []).append(k)
giving the expected:
{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}
So we iterate over the key, value pairs in sync by unpacking the tuples returned from the dictionaries .items()
method. For each pair, we set the value (i.e. 'Randy'
, 'Stan'
, 'Randy'
) as a key to a new list in the output dictionary if there is not already a list there - this is done neatly with the setdefault
method.
Because the return value from setdefault
will either be the new list we just created or the already populated list (in the case of the 'Output.txt'
pair) and the fact that lists are mutable (changes to them affect all references to them), we can just append our key ('Input.txt'
, 'Code.py'
, 'Output.txt'
) straight to whatever is returned, new or old.
Upvotes: 7