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

这是我的字典:

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

当前回答

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

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

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

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

其他回答

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

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)及以上保留,而早期的实现应该被视为未定义的顺序。

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

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

prices  = collections.OrderedDict((

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

“香蕉”

Python版本>= 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])

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

list(my_dict.keys())[0]

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

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