Skip to content Skip to sidebar Skip to footer

Is There A "stack And Map" Analogue With Dicts?

I recently had to map dict keys to values in an assessment question. I started with the following: files= {'Code.py': 'Stan', 'Output.txt': 'Randy', 'Input.txt': 'Randy'} And was

Solution 1:

You could just use a defaultdict:

from collections import defaultdict
mapped = defaultdict(list)
​
for k, v in files.items():
    mapped[v].append(k)

mapped
# defaultdict(list, {'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']})

Or use setdefault method on the dictionary:

mapped = {}
​
for k, v in files.items():
    mapped.setdefault(v, []).append(k)

mapped
# {'Stan': ['Code.py'], 'Randy': ['Output.txt', 'Input.txt']}

Or if you prefer pandas (which would not be as efficient for this task however):

s = pd.Series(files)
s.groupby(s).agg(lambda x: x.index.tolist()).to_dict()
# {'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

Timing on the small sample data:

%%timeit
from collections import defaultdict
mapped = defaultdict(list)
​
for k, v in files.items():
    mapped[v].append(k)
# 2 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%%timeit
s = pd.Series(files)
s.groupby(s).agg(lambda x: x.index.tolist()).to_dict()
# 2.12 ms ± 54.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Post a Comment for "Is There A "stack And Map" Analogue With Dicts?"