Python 你如何在字典中找到第一个键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30362391/
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
How do you find the first key in a dictionary?
提问by slagoy
I am trying to get my program to print out "banana"
from the dictionary. What would be the simplest way to do this?
我试图让我的程序"banana"
从字典中打印出来。什么是最简单的方法来做到这一点?
This is my dictionary:
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
回答by slagoy
The dict
type is an unorderedmapping, so there is no such thing as a "first" element.
该dict
类型是无序映射,因此没有“第一个”元素这样的东西。
What you want is probably collections.OrderedDict
.
你想要的大概是collections.OrderedDict
.
回答by Ryan Haining
Update:as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict
here. You can use the below approaches with a normal dict
更新:从 Python 3.7 开始,插入顺序被保留,所以你不需要OrderedDict
这里。您可以使用以下方法与正常dict
Changed in version 3.7:Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
在 3.7 版更改:字典顺序保证是插入顺序。此行为是 3.6 中 CPython 的实现细节。
Python 3.6 and earlier*
Python 3.6 及更早版本*
If you are talking about a regular dict
, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict
you will likely not get "banana"
as the first thing you see.
如果您谈论的是常规dict
,那么“第一个键”没有任何意义。钥匙不是以您可以依赖的任何方式订购的。如果你迭代你的dict
你可能不会得到"banana"
你看到的第一件事。
If you need to keep things in order, then you have to use an OrderedDict
and not just a plain dictionary.
如果您需要使事情井井有条,那么您必须使用一本OrderedDict
而不仅仅是一本普通的字典。
import collections
prices = collections.OrderedDict([
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
])
If you then wanted to see all the keys in orderyou could do so by iterating through it
如果您想按顺序查看所有键,则可以通过遍历它来执行此操作
for k in prices:
print(k)
You could, alternatively put all of the keys into a list and then work with that
您也可以将所有键放入一个列表中,然后使用它
ks = list(prices)
print(ks[0]) # will print "banana"
A faster way to get the firstelement without creating a list would be to call next
on the iterator. This doesn't generalize nicely when trying to get the nth
element though
在不创建列表的情况下获取第一个元素的更快方法是调用next
迭代器。nth
但是,在尝试获取元素时,这并不能很好地概括
>>> next(iter(prices))
'banana'
* CPython had guaranteed insertion order as an implementation detail in 3.6.
* CPython 已保证插入顺序作为 3.6 中的实现细节。
回答by kylie.a
As many others have pointed out there is no first value in a dictionary. The sorting in them is arbitrary and you can't count on the sorting being the same every time you access the dictionary. However if you wanted to print the keys there a couple of ways to it:
正如许多其他人指出的那样,字典中没有第一个值。它们中的排序是任意的,您不能指望每次访问字典时排序都是相同的。但是,如果您想打印密钥,有几种方法:
for key, value in prices.items():
print(key)
This method uses tuple assignment to access the key and the value. This handy if you need to access both the key and the value for some reason.
此方法使用元组分配来访问键和值。如果您出于某种原因需要访问键和值,这很方便。
for key in prices.keys():
print(key)
This will only gives access to the keys as the keys()
method implies.
正如keys()
方法所暗示的那样,这只会提供对密钥的访问。
回答by Mark M
Use a for loop that ranges through all keys in prices
:
使用 for 循环遍历所有键prices
:
for key, value in prices.items():
print key
print "price: %s" %value
Make sure that you change prices.items()
to prices.iteritems()
if you're using Python 2.x
如果您使用的是 Python 2.x ,请确保更改prices.items()
为prices.iteritems()
回答by maxbellec
On a Python version where dicts actually are ordered, you can do
在实际订购 dicts 的 Python 版本上,您可以执行以下操作
my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'
For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.
对于要订购的 dicts,您需要 Python 3.7+ 或 3.6+,如果您可以依赖 Python 3.6 上的 dicts 的技术和实现细节有序性质。
For earlier Python versions, there is no "first key".
对于早期的 Python 版本,没有“第一把钥匙”。
回答by ylnor
A dictionary is not indexed, but it is in some way, ordered. The following would give you the first existing key:
字典没有编入索引,但在某种程度上是有序的。以下将为您提供第一个现有密钥:
list(my_dict.keys())[0]
回答by Amit Sharma
d.keys()[0] to get the individual key.
d.keys()[0] 获取单个密钥。
Update:- @AlejoBernardin , am not sure why you said it didn't work. here I checked and it worked. import collections
更新:- @AlejoBernardin ,我不确定你为什么说它不起作用。在这里,我检查了一下,它奏效了。进口藏品
prices = collections.OrderedDict((
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
))
prices.keys()[0]
'banana'
'香蕉'
回答by turiyag
So I found this page while trying to optimize a thing for taking the only key in a dictionary of known length 1 and returning only the key. The below process was the fastest for all dictionaries I tried up to size 700.
因此,我在尝试优化事物以获取已知长度为 1 的字典中的唯一键并仅返回键时找到了此页面。以下过程是我尝试过的最大 700 的所有词典中最快的过程。
I tried 7 different approaches, and found that this one was the best, on my 2014 Macbook with Python 3.6:
我尝试了 7 种不同的方法,发现这是最好的,在我 2014 年的 Macbook 上使用 Python 3.6:
def first_5():
for key in biased_dict:
return key
The results of profiling them were:
分析它们的结果是:
2226460 / s with first_1
1905620 / s with first_2
1994654 / s with first_3
1777946 / s with first_4
3681252 / s with first_5
2829067 / s with first_6
2600622 / s with first_7
All the approaches I tried are here:
我尝试过的所有方法都在这里:
def first_1():
return next(iter(biased_dict))
def first_2():
return list(biased_dict)[0]
def first_3():
return next(iter(biased_dict.keys()))
def first_4():
return list(biased_dict.keys())[0]
def first_5():
for key in biased_dict:
return key
def first_6():
for key in biased_dict.keys():
return key
def first_7():
for key, v in biased_dict.items():
return key
回答by narwanimonish
Well as simple, the answer according to me will be
那么简单,根据我的答案将是
first = list(prices)[0]
first = list(prices)[0]
converting the dictionary to list will output the keys and we will select the first key from the list.
将字典转换为列表将输出键,我们将从列表中选择第一个键。
回答by Shital Shah
For Python 3 below eliminates overhead of list conversion:
对于下面的 Python 3,消除了列表转换的开销:
first = next(iter(prices.values()))