I’m looking for the pythonic way to create a dictionary of lists where you append values to a list for a series of keys. So a dictionary n
which stores the sum of digits for the values up to 1000, with the sum of the digits the key, for example:
n[25] = [799, 889, 898, 979, 988, 997]
Using a basic list comprehension doesn't work as it overwrites smaller values and only allows one, the largest, value per key,
n = {sumdigits(i): i for i in range(1000)}
I've got a two line working version below, but I am curious whether there is a neat one line solution to create a dictionary of variable length lists.
def sumdigits(x):
return sum(int(i) for i in str(x))
n = defaultdict(list)
for i in range(1000):
n[sumdigits(i)].append(i)
This is also a possibility that is one line (as you don't count the defaultdict initialization in your 2-line solution). With the advantage that it is significantly faster than the other solutions.
n = defaultdict(list)
{n[sum(int(d) for d in str(nb))].append(nb) for nb in range(1000)}
or really in one line (using the walrus operator python3.8 +)
{n := collections.defaultdict(list)[sum(int(i) for i in str(x))].append(x) for x in range(NB)}