问题:您如何在字典中找到第一个键?

我正在尝试"banana"从字典中打印出我的程序。最简单的方法是什么?

这是我的字典:

prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

I am trying to get my program to print out "banana" from the dictionary. What would be the simplest way to do this?

This is my dictionary:

prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

回答 0

在实际命令有序的Python版本中,您可以执行

my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'

对于要订购的字典,您需要Python 3.7+,如果可以,可以使用Python 3.6或更高版本,如果您愿意依靠Python 3.6上的技术在技术上有详细说明,那么该命令就可以了。

对于早期的Python版本,没有“第一把钥匙”。

On a Python version where dicts actually are ordered, you can do

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.

For earlier Python versions, there is no “first key”.


回答 1

字典没有索引,但是以某种方式是有序的。下面将为您提供第一个现有密钥:

list(my_dict.keys())[0]

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]

回答 2

更新:从Python 3.7开始,插入顺序得以保持,因此您无需在OrderedDict此处插入。您可以将以下方法与常规方法结合使用dict

在版本3.7中更改:保证字典顺序为插入顺序。此行为是3.6版CPython的实现细节。

资源


Python 3.6及更早版本*

如果您谈论的是常规dict,那么“第一把钥匙”没有任何意义。键没有以您可以依赖的任何方式排序。如果您遍历您的内容,dict那么您可能不会"banana"一眼就能看到。

如果您需要使事情井井有条,那么您必须使用OrderedDict而不是简单的字典。

import collections
prices  = collections.OrderedDict([
        ("banana", 4),
        ("apple", 2),
        ("orange", 1.5),
        ("pear", 3),
])

如果您随后想要查看所有键,可以依次遍历所有键

for k in prices:
    print(k)

您也可以将所有键放入列表中,然后使用该键

ks = list(prices)
print(ks[0]) # will print "banana"

在不创建列表的情况下获取第一个元素的更快方法是调用next迭代器。nth虽然尝试获取元素时这不能很好地概括

>>> next(iter(prices))
'banana'

* CPython保证了插入顺序作为3.6中的实现细节。

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

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

source


Python 3.6 and earlier*

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.

If you need to keep things in order, then you have to use an OrderedDict and not just a plain dictionary.

import collections
prices  = collections.OrderedDict([
        ("banana", 4),
        ("apple", 2),
        ("orange", 1.5),
        ("pear", 3),
])

If you then wanted to see all the keys in order you 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 first element 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(iter(prices))
'banana'

* CPython had guaranteed insertion order as an implementation detail in 3.6.


回答 3

对于下面的Python 3,消除了列表转换的开销:

first = next(iter(prices.values()))

For Python 3 below eliminates overhead of list conversion:

first = next(iter(prices.values()))

回答 4

dict类型是无序映射,因此没有“第一”元素之类的东西。

您想要的可能是collections.OrderedDict

The dict type is an unordered mapping, so there is no such thing as a “first” element.

What you want is probably collections.OrderedDict.


回答 5

因此,我在尝试优化某个东西以获取已知长度为1的字典中的唯一键并仅返回键时找到了此页面。对于我尝试过的最大尺寸为700的所有字典,以下过程是最快的。

我尝试了7种不同的方法,发现这是我使用Python 3.6的2014 Macbook上最好的方法:

def first_5():
    for key in biased_dict:
        return key

对它们进行概要分析的结果是:

  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

我尝试过的所有方法都在这里:

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

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.

I tried 7 different approaches, and found that this one was the best, on my 2014 Macbook with 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

回答 6

好吧,根据我的答案将是

first = list(prices)[0]

将字典转换为列表将输出键,我们将从列表中选择第一个键。

Well as simple, the answer according to me will be

first = list(prices)[0]

converting the dictionary to list will output the keys and we will select the first key from the list.


回答 7

正如许多其他人指出的那样,字典中没有第一个值。它们中的排序是任意的,您不能指望每次访问字典时排序都是一样的。但是,如果您要打印密钥,则有两种方法:

for key, value in prices.items():
    print(key)

此方法使用元组分配来访问键和值。如果由于某种原因需要同时访问键和值,这将非常方便。

for key in prices.keys():
    print(key)

keys()方法所暗示的那样,这将仅提供对键的访问。

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.


回答 8

d.keys()[0]获取单个密钥。

更新:-@AlejoBernardin,不知道为什么您说它不起作用。在这里,我检查了一下,它起作用了。进口馆藏

prices  = collections.OrderedDict((

    ("banana", 4),
    ("apple", 2),
    ("orange", 1.5),
    ("pear", 3),
))
prices.keys()[0]

‘香蕉’

d.keys()[0] to get the individual key.

Update:- @AlejoBernardin , am not sure why you said it didn’t work. here I checked and it worked. import collections

prices  = collections.OrderedDict((

    ("banana", 4),
    ("apple", 2),
    ("orange", 1.5),
    ("pear", 3),
))
prices.keys()[0]

‘banana’


回答 9

使用for循环,其范围为prices

for key, value in prices.items():
     print key
     print "price: %s" %value

如果使用的是Python 2.x ,请确保更改prices.items()prices.iteritems()

Use a for loop that ranges through all keys in 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


回答 10

如果您只想从字典中获得第一个键,则应使用许多以前建议的键

first = next(iter(prices))

但是,如果您想要第一个并将其余的保留为列表,则可以使用值拆包运算符

first, *rest = prices

这同样适用于价值被替换pricesprices.values()和两个键和值,你甚至可以使用拆包作业

>>> (product, price), *rest = prices.items()
>>> product
'banana'
>>> price
4

注意:您可能会想只使用first, *_ = prices第一个键,但是我通常会建议您不要使用这种用法,除非字典很短,因为它会遍历所有键并为创建一个列表rest有一些开销。

注意:如其他人所述,插入顺序是从python 3.7(或从技术上讲是3.6)及更高版本保留的,而较早的实现应视为未定义的顺序。

If you just want the first key from a dictionary you should use what many have suggested before

first = next(iter(prices))

However if you want the first and keep the rest as a list you could use the values unpacking operator

first, *rest = prices

The same is applicable on values by replacing prices with prices.values() and for both key and value you can even use unpacking assignment

>>> (product, price), *rest = prices.items()
>>> product
'banana'
>>> price
4

Note: You might be tempted to use first, *_ = prices to just get the first key, but I would generally advice against this usage unless the dictionary is very short since it loops over all keys and creating a list for the rest has some overhead.

Note: As mentioned by others insertion order is preserved from python 3.7 (or technically 3.6) and above whereas earlier implementations should be regarded as undefined order.


回答 11

最简单的方法是:

first_key = my_dict.keys()[0]

但是有些时候您应该更加小心,并确保您的实体是有价值的清单,因此:

first_key = list(my_dict.keys())[0]

easiest way is:

first_key = my_dict.keys()[0]

but some times you should be more careful and assure that your entity is a valuable list so:

first_key = list(my_dict.keys())[0]

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。