我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
当前回答
dict类型是无序映射,因此不存在“first”元素。
你想要的可能是集合。ordereddict。
其他回答
使用一个for循环遍历price中的所有键:
for key, value in prices.items():
print(key)
print("price: %s" % value)
如果使用Python 2.x,请确保将prices.items()更改为prices.iteritems()
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]
如果你只想要字典中的第一个键,你应该使用很多人之前建议的方法
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)及以上保留,而早期的实现应该被视为未定义的顺序。
正如许多人指出的那样,字典中没有第一个值。它们中的排序是任意的,不能指望每次访问字典时排序都是相同的。然而,如果你想打印这里的键,有几种方法:
for key, value in prices.items():
print(key)
该方法使用元组赋值来访问键和值。如果由于某种原因需要同时访问键和值,这很方便。
for key in prices.keys():
print(key)
这将只提供对keys()方法所暗示的键的访问。