你如何在字典中找到第一个键? [英] How do you find the first key in a dictionary?

查看:30
本文介绍了你如何在字典中找到第一个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get my program to print out "banana" from the dictionary. What would be the simplest way to do this?

这是我的字典:

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

推荐答案

在实际排序字典的 Python 版本上,你可以这样做

On a Python version where dicts actually are ordered, you can do

my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'

要订购 dicts,您需要 Python 3.7+,或者 3.6+,如果您可以依赖 Python 3.6 上的 dicts 的技术和实现细节有序性质.

For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.

对于早期的 Python 版本,没有第一把钥匙",但这会给你一把钥匙",如果只有一个钥匙,特别有用.

For earlier Python versions, there is no "first key", but this will give you "a key", especially useful if there is only one.

这篇关于你如何在字典中找到第一个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆