我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
我正试图让我的程序从字典中打印出“banana”。最简单的方法是什么?
这是我的字典:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
更新:从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 key, value in prices.items():
print(key)
该方法使用元组赋值来访问键和值。如果由于某种原因需要同时访问键和值,这很方便。
for key in prices.keys():
print(key)
这将只提供对keys()方法所暗示的键的访问。
使用一个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版本,没有“第一个键”,但这将提供“一个键”,如果只有一个键,尤其有用。
D.keys()[0]获取单个密钥。
更新: @AlejoBernardin,我不知道你为什么说它不管用。这里我检查了一下,它工作了。 进口集合
prices = collections.OrderedDict((
("banana", 4),
("apple", 2),
("orange", 1.5),
("pear", 3),
))
prices.keys()[0]
“香蕉”
更新:我决定在2023年1月,在我的Windows 11 PC上,用Ryzen 9 5900x再次测试它。为了让我更容易重新运行它(亲爱的读者,你也可以轻松地运行它),我在这里做了一个Gist: https://gist.github.com/maludwig/d38054ec05d01ad91df5dade8aa47d9d
结果出来了,first_5仍然是赢家!
12100238 / s with first_1
9094216 / s with first_2
9219988 / s with first_3
7370554 / s with first_4
13525210 / s with first_5
9810076 / s with first_6
8676864 / s with first_7
一切都快得多(CPU也更好,因为距离第一次测试已经过去几年了)。但是显然也做了优化(详见评论),特别是在first_1中。
first_1 is 5.43x faster
first_2 is 4.77x faster
first_3 is 4.62x faster
first_4 is 4.15x faster
first_5 is 3.67x faster
first_6 is 3.47x faster
first_7 is 3.34x faster
Current scoreboard:
#1: first_5 (previously #1)
#2: first_1 (previously #4)
#3: first_6 (previously #2)
#4: first_3 (previously #5)
#5: first_2 (previously #6)
#6: first_7 (previously #3)
#7: first_4 (previously #7)
因此,当我试图优化一个东西,以获取已知长度为1的字典中的唯一键并仅返回该键时,我发现了这个页面。下面的过程是我尝试的所有700大小的字典中最快的。
我尝试了7种不同的方法,发现这个方法是最好的,在我2014年的Macbook上,使用Python 3.6:
def first_5():
for key in biased_dict:
return key
分析结果如下:
2226460 / s with first_1
1905620 / s with first_2
1994654 / s with first_3
1777946 / s with first_4
3681252 / s with first_5
2829067 / s with first_6
2600622 / s with first_7
以下是我尝试过的所有方法:
def first_1():
return next(iter(biased_dict))
def first_2():
return list(biased_dict)[0]
def first_3():
return next(iter(biased_dict.keys()))
def first_4():
return list(biased_dict.keys())[0]
def first_5():
for key in biased_dict:
return key
def first_6():
for key in biased_dict.keys():
return key
def first_7():
for key, v in biased_dict.items():
return key
如果你只想要字典中的第一个键,你应该使用很多人之前建议的方法
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)及以上保留,而早期的实现应该被视为未定义的顺序。
假设你想打印第一个键:
print(list(prices.keys())[0])
如果你想打印第一个键的值:
print(prices[list(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])