在Python字典中提取第n个键? [英] Extract the nth key in a python dictionary?

查看:1190
本文介绍了在Python字典中提取第n个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个python字典和一个整数n,我需要访问第n个键.我需要在项目中多次重复执行此操作.

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?

推荐答案

我想您想做这样的事情,但是由于字典没有任何顺序,因此dic.keys中的键顺序可以是任意值:

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'

这篇关于在Python字典中提取第n个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆