[Python-ideas] factory for efficient creation of many dicts with the same keys

Sergey Fedoseev fedoseev.sergey at gmail.com
Fri Sep 8 09:34:41 EDT 2017


Hi all,

Sometimes you may need to create many dicts with the same keys, but different
values. For example, if you want to return data from DB as dicts.

I think that special type could be added to solve this task more effectively.
I created proof of concept for this and here's benchmarks:

# currently the fastest way to do it AFAIK
$ ./python -m timeit -s "nkeys = 5; nrows = 1000; rows = [(i,)*nkeys
for i in range(nrows)]; enumerated = list(enumerate(range(nkeys)))"
"for row in rows: {key: row[i] for i, key in enumerated}"
500 loops, best of 5: 645 usec per loop

$ ./python -m timeit -s "nkeys = 5; nrows = 1000; rows = [(i,)*nkeys
for i in range(nrows)]; factory = dict.factory(*range(nkeys)); from
itertools import starmap" "for d in starmap(factory, rows): d"
5000 loops, best of 5: 81.1 usec per loop

I'd like to write a patch if this idea will be accepted.


More information about the Python-ideas mailing list