grab dict keys/values without iterating ?!
Peter Otten
__peter__ at web.de
Wed Dec 11 07:10:52 EST 2013
Tamer Higazi wrote:
> Hi Dave!
>
> You were absolutely right.
> I don't want to iterate the entire dict to get me the key/values
>
> Let us say this dict would have 20.000 entries, but I want only those
> with "Aa" to be grabed.
> Those starting with these 2 letters would be only 5 or 6 then it would
> take a lot of time.
>
> In which way would you prefer to store the data, and which functions or
> methods would you use effectively to accomplish this task ?
Well, Dave already gave one approach:
[Dave Angel]
> For example if you stored all the keys in a sorted list you could use
> bisect.
See also http://docs.python.org/dev/library/bisect.html
Another option would be to use a database. Assuming the table 'lookup' has
two columns 'key' and 'value' you'd get the matching rows with
select key, value from lookup where key like 'Aa%';
A lightweight database that comes with Python is sqlite:
http://docs.python.org/dev/library/sqlite3.html
http://www.sqlite.org/
More information about the Python-list
mailing list