Filip Allberg
Filip Allberg

Reputation: 5171

Python performance difference between dictionary look-ups (string keys) to list indexing

Compared to indexing list using integers, i.e. l[4], how slow is indexing a Python dictionary that use short strings for keys? I know the theoretical worst-case here; but is Python doing any optimizations under the hood making the practical difference negligible?

My keys are either a single lowercase letter or two uppercase letters making for at most 26+26*26=702 keys. The average number of keys is very small, < 50. Extending the existing solution to convert keys into integers, adjusting for gaps, and using lists instead of dictionaries is not a hard problem but if the performance difference is negligible then there is not really any point.

Upvotes: 2

Views: 1696

Answers (1)

hyperneutrino
hyperneutrino

Reputation: 5425

It seems that lists are faster:

LIST

DICT

This makes sense: random access by numbers works fairly quickly, but with dict keys, the getter must first be hashed which slows it down significantly enough that you can kind of notice the distance after 128 ** 3 accesses.

Really, the difference is negligible, and depending on your uses, a dict may be better where you need key: value. For speed though, lists are better, but if your access keys aren't just integers, dicts are probably better.

Upvotes: 3

Related Questions