2
\$\begingroup\$

Is there a faster way of getting the key of 1 or 2 by using the accs value for my getID function? Unfortunately I cannot use an inverse dict due to the fact I'm using a list for the value which causes a unhasable list error. Mainly I'm worried more when the db gets larger in size the getID function will take longer to loop through the db.

db = {"users":{"1":{"main":"charles","accs":["charles","ashketchum"],"rank":4},"2":{"main":"don","accs":["don","donny"],"rank":4}}}
class user_data:

    def get(name, key):
        key = key.lower()
        if key in db["users"][name]:
            return db["users"][name][key]
        else:
            return None

    def getID(name):
        name = name.lower()
        for key in db["users"].keys():
            if name in db["users"][key]["accs"]:
                return key
        return None

Note: the accs value will change as well.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Why not use a set? For a set in is O(1). You can extend the set by adding another acc with db['users']['1']['accs'].add('misty') (add instead of append). After this change your lookup is only O(n), where n is the number of users (at worst) and in reality will depend on where the user is in the internal representation of the dict.

Alternatively you could just use a tuple (which is hashable). This just makes it different to add another account to a user:

db['users']['1']['accs'] += ("misty",)

This way you could build the reverse dictionary, speeding the lookup up to O(1). However, you would have to keep the reversed and actual db in sync.

In addition, to iterate over the keys of a dict, it is sufficient to do:

for key in db['users']:

But here I would actually do:

for key, user in db['users'].items():
    if name in user['accs']:
        return key

You don't need the explicit return None because None is already the default return value of a function in python.

Your function get(name, key) is confusing, because name is actually id (so "1", "2", ...).

Python has an official style guide, PEP8. One of the things it recommend is using lower_case for variable and function names.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.