如何访问字典中的第一个和最后一个元素?

编程入门 行业动态 更新时间:2024-10-28 12:16:31
本文介绍了如何访问字典中的第一个和最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

发布之前,我已经经历过>访问字典中的任意元素在Python中,但对此我不确定.

Before posting, I have already gone through Access an arbitrary element in a dictionary in Python, butI'm uncertain about this.

我有一个很长的字典,我必须获取它的第一个和最后一个键的值.我可以使用dict[dict.keys()[0]]和dict[dict.keys()[-1]]来获取第一个和最后一个元素,但是由于key:value对是以随机形式输出的(如key:value对的位置是随机的),将提供解决方案吗在此链接中始终有效吗?

I have a long dictionary and I've to get the values of its first and last keys. I can use dict[dict.keys()[0]] and dict[dict.keys()[-1]] to get the first and last elements, but since the key:value pairs are outputted in a random form(as in the positioning of the key:value pairs is random), will the solution provided in this link always work?

推荐答案

使用 OrderedDict ,因为普通字典在遍历时不会保留其元素的插入顺序.方法如下:

Use an OrderedDict, because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how:

# import the right class from collections import OrderedDict # create and fill the dictionary d = OrderedDict() d['first'] = 1 d['second'] = 2 d['third'] = 3 # retrieve key/value pairs els = list(d.items()) # explicitly convert to a list, in case it's Python 3.x # get first inserted element els[0] => ('first', 1) # get last inserted element els[-1] => ('third', 3)

更多推荐

如何访问字典中的第一个和最后一个元素?

本文发布于:2023-10-18 06:10:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1503358.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   字典   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!