我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?

这是我的字典:

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

当前回答

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

更新: @AlejoBernardin,我不知道你为什么说它不管用。这里我检查了一下,它工作了。 进口集合

prices  = collections.OrderedDict((

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

“香蕉”

其他回答

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

list(my_dict.keys())[0]

dict类型是无序映射,因此不存在“first”元素。

你想要的可能是集合。ordereddict。

假设你想打印第一个键:

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

如果你想打印第一个键的值:

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

如果你只想要字典中的第一个键,你应该使用很多人之前建议的方法

first = next(iter(prices))

然而,如果你想要第一个并保留其余的列表,你可以使用值解包操作符

first, *rest = prices

这同样适用于用prices.values()替换price的值,对于key和value,你甚至可以使用unpacking赋值

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

注意:您可能会倾向于使用first, *_ = prices来获取第一个键,但我通常建议不要使用这种方法,除非字典非常短,因为它会循环遍历所有键,并且为其余的键创建一个列表会有一些开销。

注意:正如其他人所提到的,插入顺序从python 3.7(或技术上3.6)及以上保留,而早期的实现应该被视为未定义的顺序。

更新:我决定在2023年1月,在我的Windows 11 PC上,用Ryzen 9 5900x再次测试它。为了让我更容易重新运行它(亲爱的读者,你也可以轻松地运行它),我在这里做了一个Gist: https://gist.github.com/maludwig/d38054ec05d01ad91df5dade8aa47d9d

结果出来了,first_5仍然是赢家!

12100238 / s with first_1
 9094216 / s with first_2
 9219988 / s with first_3
 7370554 / s with first_4
13525210 / s with first_5
 9810076 / s with first_6
 8676864 / s with first_7

一切都快得多(CPU也更好,因为距离第一次测试已经过去几年了)。但是显然也做了优化(详见评论),特别是在first_1中。

first_1 is 5.43x faster
first_2 is 4.77x faster
first_3 is 4.62x faster
first_4 is 4.15x faster
first_5 is 3.67x faster
first_6 is 3.47x faster
first_7 is 3.34x faster

Current scoreboard:
  #1: first_5 (previously #1)
  #2: first_1 (previously #4)
  #3: first_6 (previously #2)
  #4: first_3 (previously #5)
  #5: first_2 (previously #6)
  #6: first_7 (previously #3)
  #7: first_4 (previously #7)


因此,当我试图优化一个东西,以获取已知长度为1的字典中的唯一键并仅返回该键时,我发现了这个页面。下面的过程是我尝试的所有700大小的字典中最快的。

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

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