我正试图让我的程序从字典中打印出“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]

“香蕉”

其他回答

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

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

prices  = collections.OrderedDict((

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

“香蕉”

使用一个for循环遍历price中的所有键:

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

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

假设你想打印第一个键:

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

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

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

更新:从Python 3.7开始,插入顺序保持不变,所以这里不需要OrderedDict。你可以对普通字典使用以下方法

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


Python 3.6及更早版本*

如果你在谈论一个普通的字典,那么“第一个键”就没有任何意义。这些键没有按照您可以依赖的任何方式进行排序。如果你重复你的字典,你可能不会看到“香蕉”作为你看到的第一个东西。

如果您需要保持内容的有序,那么您必须使用OrderedDict,而不仅仅是普通的字典。

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

如果你想依次查看所有的键,你可以通过遍历它来做到这一点

for k in prices:
    print(k)

你也可以,把所有的键放到一个列表中,然后使用它

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

在不创建列表的情况下获取第一个元素的更快方法是在迭代器上调用next。但是,当尝试得到第n个元素时,这并不能很好地推广

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

CPython在3.6中保证了插入顺序。

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

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