我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
当前回答
字典没有索引,但在某种程度上是有序的。下面将为您提供第一个现有密钥:
list(my_dict.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版本,没有“第一个键”,但这将提供“一个键”,如果只有一个键,尤其有用。
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])
假设你想打印第一个键:
print(list(prices.keys())[0])
如果你想打印第一个键的值:
print(prices[list(prices.keys())[0]])
字典没有索引,但在某种程度上是有序的。下面将为您提供第一个现有密钥:
list(my_dict.keys())[0]