Dict.setdefault inserts a sort into the list… here is a solution to the problem.
Dict.setdefault inserts a sort into the list
I was wondering if there was a way to append to sorted dictionary list fields using lambda-like styles.
Example:
a = {}
a.setdefault("foo", []).append(2)
a.setdefault("foo", []).append(1)
{'foo': [2, 1]}
Is there a way to insert in sort order
like using a["foo"].bisect.insort(a, -1)
so that I don’t need to call sort later?
Solution
Everything you need is in Python’s standard library:
import bisect
from collections import defaultdict
def add(dd, key, value):
bisect.insort_left(dd[key], value)
a = defaultdict(list)
add(a, "foo", 3)
add(a, "foo", 2)
add(a, "foo", 1)
add(a, "foo", 3)
add(a, "foo", 2)
add(a, "foo", 1)
assert a["foo"] == sorted(a["foo"])
print(a)
If you want a lambda:
add = lambda dd, key, value: bisect.insort_left(dd[key], value)
In terms of performance, using the sort
runtime afterwards should be faster than using bisect.insort_left
. In both cases, the runtime complexity is O(n log n), but the function call overhead should result in different absolute run times.