Extract the nth key in a python dictionary?
Question:
Given a python dictionary and an integer n
, I need to access the n
th 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'
dict.keys()
returns a list so, all you need to do is dict.keys()[n]
But, a dictionary is an unordered collection so nth element does not make any sense in this context.
Note: Indexing dict.keys()
is not supported in python3
For those that want to avoid the creation of a new temporary list just to access the nth element, I suggest to use an iterator.
from itertools import islice
def nth_key(dct, n):
it = iter(dct)
# Consume n elements.
next(islice(it, n, n), None)
# Return the value at the current position.
# This raises StopIteration if n is beyond the limits.
# Use next(it, None) to suppress that exception.
return next(it)
This can be notably faster for very large dictionaries compared to converting the keys into a temporary list first and then accessing its nth element.
It is mentioned in multiple answers, that dictionaries were unordered. This is nonly true for python versions up to 3.6. From 3.7 ongoing, dictionaries are in fact ordered.
Given a python dictionary and an integer n
, I need to access the n
th 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 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'
dict.keys()
returns a list so, all you need to do is dict.keys()[n]
But, a dictionary is an unordered collection so nth element does not make any sense in this context.
Note: Indexing
dict.keys()
is not supported in python3
For those that want to avoid the creation of a new temporary list just to access the nth element, I suggest to use an iterator.
from itertools import islice
def nth_key(dct, n):
it = iter(dct)
# Consume n elements.
next(islice(it, n, n), None)
# Return the value at the current position.
# This raises StopIteration if n is beyond the limits.
# Use next(it, None) to suppress that exception.
return next(it)
This can be notably faster for very large dictionaries compared to converting the keys into a temporary list first and then accessing its nth element.
It is mentioned in multiple answers, that dictionaries were unordered. This is nonly true for python versions up to 3.6. From 3.7 ongoing, dictionaries are in fact ordered.