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?
解决方案
I guess you wanted to do something like this, but as dictionary don't have any order so the order of keys in dic.keys can be anything:
def ix(self, dic, n): #don't use dict as a variable name
try:
return list(dic)[n] # or sorted(dic)[n] if you want the keys to be sorted
except IndexError:
print 'not enough keys'