0

I know dictionaries are fast when it comes to looking up a key but is it a waste, especially in respect to memory, to have two dictionaries point to the same exact same objects but with different yet relevant keys so you can use those keys to look up elements in different ways. In my application lookup speed is more important than the time to arrange the set of data.

Ex: you have a large set containing driver's license information. You store the information in a Dictionary with the key being their respective name on the drivers license. You also create a second Dictionary pointing to the same objects as the key but with the drivers license ID number as the key

class DL:
    def __init__(self, name, id):
        self.name = name
        self.id = id

licenses = {DL('jon', 1), DL('joe', 2), DL('jack', 3), DL('jill', 4)}
byName = dict()
byID = dict()

for i in licenses:
    byName[i.name] = i
    byID[i.id] = i 

print(byName)
print(byID)
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • See whether it can address your issue: https://stackoverflow.com/questions/11105115/data-structure-to-implement-a-dictionary-with-multiple-indexes – Ken Lee Dec 20 '20 at 01:56
  • 1
    @KenLee that's literally just two dictionaries... – juanpa.arrivillaga Dec 20 '20 at 01:57
  • 3
    It's a tradeoff. Whether or not it is worth it is up to you given your project requirements. – juanpa.arrivillaga Dec 20 '20 at 01:57
  • Well, I don't know if it's worth it based on my requirements. I want as fast as possible lookups which this provides I think but at what expense. how much of the dict + its data will be dict. What's stopping me from doing this with every attribute in an object besides laziness and conveniance. –  Dec 20 '20 at 02:12
  • 1
    No, it's not bad practice, this is fine. Just be sensible about it and package things together if they need to be synchronized. – Veedrac Dec 20 '20 at 10:55

1 Answers1

0

One versus two dictionaries is not substantially going to affect your algorithm's speed in the sense of time complexity. They're still hashmaps, and that means worst case O(N) lookups with average case O(1) lookups.

Read more on python dictionary time complexity here: https://wiki.python.org/moin/TimeComplexity

It should be noted, Python has highly optimized hash functions for integers and strings, so if you find yourself concocting something custom to support a single dictionary, it's probably a bad idea perf-wise.

If absolute perf is important to you, your low hanging fruit improvements likely lie elsewhere.

Tumbleweed53
  • 1,491
  • 7
  • 13