在没有迭代的情况下,在字典中任意选择一个键 [英] Choose one key arbitrarily in a dictionary without iteration

查看:158
本文介绍了在没有迭代的情况下,在字典中任意选择一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想确保在Python字典中没有办法得到一个键(没有特定的质量或与某个值的关系),而是进行迭代。就像我发现,你必须通过遍历整个字典循环来列出它们。这样的东西:

  list_keys = [k for d in dic.keys()] 

事情是我只需要一个任意键,如果字典不是空的,不关心其余的。我猜,除了创建一个长列表,只是随机获取一个关键是一个很长的开销,不是吗?
有没有更好的技巧有人可以指出?



谢谢

解决方案

这里的很多答案都会产生一个随机的键,但原始问题要求使用任意键。这两者之间有很大的区别。随机性具有少量的数学/统计保证。



Python字典没有以任何有意义的方式排列。所以,是的,访问任意密钥需要迭代。但是对于单个任意键,我们不需要遍历整个字典。内置函数 next iter 在这里非常有用:

  key = next(iter(mapping))

内置的 iter 在映射中的键上创建一个迭代器。迭代顺序将是任意的。内置的 next 从迭代器返回第一个项目。迭代整个映射对于任意密钥不是必需的。



如果要最终从映射中删除密钥,可以使用 dict.popitem 。这是docstring:

  D.popitem() - > (k,v),删除并返回一些(键值)对作为2元组; 
但如果D为空,则引发KeyError。


I just wanna make sure that in Python dictionaries there's no way to get just a key (with no specific quality or relation to a certain value) but doing iteration. As much as I found out you have to make a list of them by going through the whole dictionary in a loop. Something like this:

list_keys=[k for k in dic.keys()]

The thing is I just need an arbitrary key if the dictionary is not empty and don't care about the rest. I guess iterating over a long dictionary in addition to creation of a long list for just randomly getting a key is a whole lot overhead, isn't it? Is there a better trick somebody can point out?

Thanks

解决方案

A lot of the answers here produce a random key but the original question asked for an arbitrary key. There's quite a difference between those two. Randomness has a handful of mathematical/statistical guarantees.

Python dictionaries are not ordered in any meaningful way. So, yes, accessing an arbitrary key requires iteration. But for a single arbitrary key, we do not need to iterate the entire dictionary. The built-in functions next and iter are useful here:

key = next(iter(mapping))

The iter built-in creates an iterator over the keys in the mapping. The iteration order will be arbitrary. The next built-in returns the first item from the iterator. Iterating the whole mapping is not necessary for an arbitrary key.

If you're going to end up deleting the key from the mapping, you may instead use dict.popitem. Here's the docstring:

D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple;
but raise KeyError if D is empty.

这篇关于在没有迭代的情况下,在字典中任意选择一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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