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

这是我的字典:

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

当前回答

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

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

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

其他回答

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

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

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

更新:我决定在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

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

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

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

假设你想打印第一个键:

print(list(prices.keys())[0])

如果你想打印第一个键的值:

print(prices[list(prices.keys())[0]])