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

这是我的字典:

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

当前回答

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

其他回答

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

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

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

在字典是有序的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]])

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

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

prices  = collections.OrderedDict((

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

“香蕉”

很简单,根据我的答案将是

第一个=列表(价格)[0]

将字典转换为列表将输出键,并从列表中选择第一个键。