1

I would like to store a lot of instances of some data in python. Each record has the following fields: username, address, salary etc...

The username should be unique. I do a lot of searches.

Currently I am using a list of dictionaries, but when I insert a new item I iterate the list and check the username of each dictionary, which is O(n). Searching is O(n) too. How could I achieve that there is an index on usernames, and make the search time O(logn)?

5
  • Generally, the way to get to O(log n) is with binary searching, which suggests ordering your list alphabetically by username. If usernames are unique, why not just use an outer dictionary, though? Commented Sep 7, 2015 at 14:13
  • 1
    Why not use a dictionary with the usernames as keys? Commented Sep 7, 2015 at 14:13
  • 2
    Why mimic a relational database, when you can use a relational database (like sqlite). Commented Sep 7, 2015 at 14:17
  • Dictionary with username as a key gives you O(1) lookup time. Commented Sep 7, 2015 at 14:18
  • i guess you have to provide a sample of your data that you want to use. I cant imagine how you would get a db with unique username. Doesnt seem right and probably this is a bad idea. If this is a really small project you have already one or two answers on the table. Commented Sep 8, 2015 at 18:04

2 Answers 2

2

Why not use a dictionary of dicts?

The top-level dictionary could be addressed by the username and the other dicts can be the same you have now.

A dictionary can also be scanned threw (d.values()) -- the only disadvantage is, that you can't depend on the ordering.

Of course that is not a DB behavior, but in most cases good enough and very fast -- the access via dict is O(1).

Of course you could use sqlite -- but when you just want to access via username and scan the entries, you are much faster (both in development- and runtime speed).

Sign up to request clarification or add additional context in comments.

Comments

2

You could alternatively actually use a relational database. The sqlite module allows for databases in memory:

import sqlite3
conn = sqlite3.connect(':memory:')
# ...
conn.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.