somecallmemike
somecallmemike

Reputation: 441

Find all keys >= integer in Python dictionary

Say I have the following dictionary of epoch time keys:

dict = {
  "1363017884": "some val",
  "1363033813": "another val",
}

I would like to find all keys greater than say 1363033000 (in this case only 1363033813 would match). I have a for loop that checks each key, but this seems so inefficient:

for epoch,value in dict.iteritems():
  if int(epoch) >= 1363033000:
    do something interesting

Upvotes: 0

Views: 2015

Answers (3)

Pontios
Pontios

Reputation: 2394

If you have numbers and strings as keys in the dictionary first do that

myStringsList = [s for s in dictFromFile.keys() if s.isdigit()]

This will give you a list with the numbers as string.

Then convert the string list to an int list and get only the > than X elements:

myFinalList = [s for s in map(int, mynewlist) if s > X] 

Hope it helps!

Upvotes: 0

Jay P.
Jay P.

Reputation: 651

You could slightly modify the code from here to add a large_keys attribute. Now, whenever one of those large epochs gets added, the dict will keep track of them. When you want to iterate over them, you can simply iterate over that attribute.

class MyUpdateDict(dict):
    def __init__(self, *args, **kwargs):
        self.large_keys = []
        self.update(*args, **kwargs)

    def __setitem__(self, key, value):
        # optional processing here
        if int(key)>1363033000:
            self.large_keys.append((key,value))
        super(MyUpdateDict, self).__setitem__(key, value)

    def update(self, *args, **kwargs):
        if args:
            if len(args) > 1:
                raise TypeError("update expected at most 1 arguments, got %d" % len(args))
            other = dict(args[0])
            for key in other:
                self[key] = other[key]
        for key in kwargs:
            self[key] = kwargs[key]

    def setdefault(self, key, value=None):
        if key not in self:
            self[key] = value
        return self[key]

This might be overly simplistic, because the large value is hard-coded, but you can modify to make it a bit more appropriate.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123480

Looping over the dictionary is the only real choice you have, there is no more efficient method.

Or you could use a different data structure; storing integers connected to values in a btree structure for example would make searching for keys greater than or lower than a given search value much more efficient.

Upvotes: 7

Related Questions