简体   繁体   English

你如何找到字典中的第一个关键字?

[英]How do you find the first key in a dictionary?

I am trying to get my program to print out "banana" from the dictionary.我想让我的程序从字典中打印出"banana" What would be the simplest way to do this?最简单的方法是什么?

This is my dictionary:这是我的词典:

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

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 版本,没有“第一把钥匙”。

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]

Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict here.更新:从 Python 3.7 开始,插入顺序得到维护,因此这里不需要OrderedDict You can use the below approaches with a normal dict您可以将以下方法与普通dict

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.在 3.7 版更改:字典顺序保证是插入顺序。 This behavior was an implementation detail of CPython from 3.6.此行为是 3.6 中 CPython 的实现细节。

source 来源


Python 3.6 and earlier* Python 3.6 及更早版本*

If you are talking about a regular dict , then the "first key" doesn't mean anything.如果您谈论的是常规dict ,那么“第一个键”没有任何意义。 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您可能不会首先看到"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 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.在不创建列表的情况下获取第一个元素的更快方法是在迭代器上调用next This doesn't generalize nicely when trying to get the nth element though尽管在尝试获取第nth元素时,这并不能很好地概括

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

* CPython had guaranteed insertion order as an implementation detail in 3.6. * CPython 已保证插入顺序作为 3.6 中的实现细节。

I am trying to get my program to print out "banana" from the dictionary.我正在尝试让我的程序从字典中打印"banana" What would be the simplest way to do this?最简单的方法是什么?

This is my dictionary:这是我的字典:

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

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通过用prices.values()替换prices ,同样适用于值,对于键和值,您甚至可以使用解包赋值

>>> (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.注意:您可能想先使用first, *_ = prices来获取第一个键,但我通常建议不要使用这种用法,除非字典非常短,因为它会遍历所有键并为rest键创建一个列表有一些高架。

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.注意:正如其他人提到的,插入顺序是从python 3.7 (或技术上 3.6)及更高版本中保留的,而早期的实现应被视为未定义的顺序。

The dict type is an unordered mapping, so there is no such thing as a "first" element. dict类型是无序映射,因此没有“第一个”元素这样的东西。

What you want is probably collections.OrderedDict .你想要的可能是collections.OrderedDict

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.因此,我在尝试优化事物以获取已知长度为 1 的字典中的唯一键并仅返回键时找到了此页面。 The below process was the fastest for all dictionaries I tried up to size 700.以下过程是我尝试过的最大 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

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.将字典转换为列表将输出键,我们将从列表中选择第一个键。

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()方法所暗示的那样提供对keys()访问。

Assuming you want to print the first key:假设您要打印第一个键:

print(list(prices.keys())[0])

If you want to print first key's value:如果要打印第一个键的值:

print(prices[list(prices.keys())[0]])

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()

d.keys()[0] to get the individual key. d.keys()[0] 获取单个密钥。

Update:- @AlejoBernardin , am not sure why you said it didn't work.更新:- @AlejoBernardin ,我不确定你为什么说它不起作用。 here I checked and it worked.在这里,我检查了一下,它奏效了。 import collections进口藏品

prices  = collections.OrderedDict((

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

'banana' '香蕉'

Use the one liner below which is quite logical and fast.使用下面的一个班轮,这是非常合乎逻辑和快速的。 On a for loop just call break imediatelly to exit and have the values.在 for 循环中,只需立即调用 break 即可退出并获取值。

for first_key in prices:  break
print(first_key)

If you also want the key and the value.如果您还想要键和值。

for first_key, first_value in prices.items():  break
print(first_key, first_value)

Python version >= 3.7 # where dictionaries are ordered Python version >= 3.7 # 字典排序的地方

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

# you can create a list of keys using list(prices.keys())

prices_keys_list = list(prices.keys())

# now you can access the first key of this list 

print(prices_keys_list[0])   # remember 0 is the first index

# you can also do the same for values using list(prices.values())

prices_values_list = list(prices.values())

print(prices_values_list[0])

This will work in Python 2 but won't work in Python 3 ( TypeError: 'dict_keys' object is not subscriptable ):这将在 Python 2 中工作,但在 Python 3 中不起作用TypeError: 'dict_keys' object is not subscriptable ):

first_key = my_dict.keys()[0]  

For a small list, if eg you get a response as a dict and it is one element you can convert it to list first:对于一个小列表,例如,如果您得到一个 dict 响应并且它是一个元素,您可以先将其转换为列表:

assert len(my_dict)==1
key = list(my_dict.keys())[0]

If its a rather long dict, better use the method sujested by @Ryan as it should be more efficient.如果它是一个相当长的字典,最好使用@Ryan 推荐的方法,因为它应该更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM