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

这是我的字典:

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

当前回答

假设你想打印第一个键:

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

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

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

其他回答

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

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

在字典是有序的Python版本中,你可以这样做

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

对于字典的排序,你需要Python 3.7+,如果你愿意依赖CPython 3.6上字典的技术上实现细节的排序性质,则需要Python 3.6+。

对于早期的Python版本,没有“第一个键”,但这将提供“一个键”,如果只有一个键,尤其有用。

假设你想打印第一个键:

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中保证了插入顺序。

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

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

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