Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the nth key in a python dictionary?

Tags:

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?

like image 560
Hemanth Malla Avatar asked Jun 07 '13 06:06

Hemanth Malla


People also ask

How do I extract a key in Python?

Method 1 : Using List. Step 1: Convert dictionary keys and values into lists. Step 2: Find the matching index from value list. Step 3: Use the index to find the appropriate key from key list.

How do you slice a dictionary key in Python?

Given dictionary with value as lists, slice each list till K. Input : test_dict = {“Gfg” : [1, 6, 3, 5, 7], “Best” : [5, 4, 2, 8, 9], “is” : [4, 6, 8, 4, 2]}, K = 3 Output : {'Gfg': [1, 6, 3], 'Best': [5, 4, 2], 'is': [4, 6, 8]} Explanation : The extracted 3 length dictionary value list.

How do you get the next key in a dictionary?

In this, we convert the dictionary to iterator using iter() and then extract the next key using next().


2 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' 
like image 102
Ashwini Chaudhary Avatar answered Oct 02 '22 23:10

Ashwini Chaudhary


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

like image 33
shyam Avatar answered Oct 03 '22 00:10

shyam