Answer a question

Given a python dictionary and an integer n, I need to access the nth key. I need to do this repeatedly many times in my project.

I have written a function which does this:

def ix(self,dict,n):
    count=0
    for i in sorted(dict.keys()):
        if n==count:
            return i
        else:
            count+=1

But the problem is that if the dictionary is huge, the time complexity increases when used repeatedly.

Is there an efficient way to do this?

Answers

I guess you wanted to do something like this, but as dictionary don't have any order so the order of keys in dict.keys can be anything:

def ix(self, dct, n): #don't use dict as  a variable name
   try:
       return list(dct)[n] # or sorted(dct)[n] if you want the keys to be sorted
   except IndexError:
       print 'not enough keys'
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐