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?
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.
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.
In this, we convert the dictionary to iterator using iter() and then extract the next key using next().
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With