提取python字典中的第n个键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16977385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract the nth key in a python dictionary?
提问by Hemanth Malla
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.
给定一个 python 字典和一个 integer n,我需要访问nth 键。我需要在我的项目中多次重复执行此操作。
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?
有没有一种有效的方法来做到这一点?
采纳答案by Ashwini Chaudhary
I guess you wanted to do something like this, but as dictionary don't have any order so the order of keys in dic.keyscan be anything:
我猜你想做这样的事情,但是因为字典没有任何顺序,所以键的顺序dic.keys可以是任何东西:
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'
回答by shyam
dict.keys()returns a list so, all you need to do is dict.keys()[n]
dict.keys()返回一个列表,所以你需要做的就是 dict.keys()[n]
But, a dictionary is an unordered collection so nth element does not make any sense in this context
但是,字典是一个无序的集合,所以第 n 个元素在这种情况下没有任何意义
回答by normanius
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.
对于那些想要避免创建新的临时列表只是为了访问第 n 个元素的人,我建议使用迭代器。
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.
与首先将键转换为临时列表然后访问其第 n 个元素相比,这对于非常大的字典来说可以明显更快。

