【问题标题】:How do you find the first item in a dictionary? [duplicate]如何找到字典中的第一项? [复制]
【发布时间】:2020-07-28 06:00:18
【问题描述】:

我正在尝试获取我在字典中插入的第一个项目(尚未重新排序)。 例如:

_dict = {'a':1, 'b':2, 'c':3}

我想得到元组('a',1)

我该怎么做?

【问题讨论】:

  • 这已经被问过了here
  • @yatu 确实,事实上我在自己的回答中提到了它。但是他们没有区分 python 2、3 和 >=3.6,因此这是我在对你提到的那个答案感到困惑之后的贡献,并环顾四周
  • 第一个不要,但是貌似在第三个答案stackoverflow.com/a/30362701/9698684

标签: python dictionary ordereddictionary


【解决方案1】:

在 Python 3.6 之前,字典是无序的,因此“first”没有很好的定义。如果您想保留广告订单,则必须使用OrderedDicthttps://docs.python.org/2/library/collections.html#collections.OrderedDict

从 Python 3.6 开始,字典默认保持插入顺序(参见How to keep keys/values in same order as declared?

知道这一点,你只需要这样做

first_element = next(iter(_dict.items()))

请注意,由于_dict.items() 不是迭代器而是可迭代的,因此您需要通过调用iter 为其创建一个迭代器。

键和值也可以这样做:

first_key = next(iter(_dict))
first_value = next(iter(_dict.values()))

【讨论】:

  • 你想在这里做什么?自己发布问题并同时回答?
  • 是的,这是一个问答(只需尝试“提问”,您就会看到 Stackoverflow 为您提供了这样做的可能性)。我这样做是因为你在谷歌上输入了那个问题,第一个结果已经过时了:stackoverflow.com/questions/30362391/…
  • 这实际上在 SO 中很常见,也受到鼓励。我提到的链接中也提到了@MayankPorwal
  • 我的错。同意。
猜你喜欢
  • 2015-08-02
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 2017-11-29
  • 2020-08-12
  • 1970-01-01
  • 2017-11-27
相关资源
最近更新 更多